Unit 2C++
Unit 2C++
Unit 2C++
UNIT II
Classes and Objects &Constructors and Destructor: Classes in C++, Declaring Objects,
Access Specifiers and their Scope, Defining Member Function, Overloading Member Function,
Nested class, Constructors and Destructors, Introduction, Constructors and Destructor,
Characteristics of Constructor and Destructor, Application with Constructor, Constructor with
Arguments parameterized Constructor, Destructors, Anonymous Objects.
CLASSES IN C++
A class is used to pack data members and member function together. The class has a mechanism
to prevent direct access to its members, which is the central idea of object-oriented
programming. The class declaration is also known as formation of new abstract data type. The
abstract data type can be used as basic data type such as int, float, etc.
Syntax:
member function
Functions that are defined inside the class is known as member function
Access specifier
It can control data members and member functions
It is categorized into three types
1.private: It can be accessible within the class
2.protected: It can be accessible within the class or within in the subclass
3.public: It can be accessible in any point of the program.
Example:
class Test
{
private:
int data1;
float data2;
public:
void function1()
{
data1 = 2;
}
float function2()
{
data2 = 3.5;
return data2;
}
};
DECLARING OBJECTS
The declaration of objects is same as declaration of variables of basic data types. Defining
objects of class data type is known as class instantiation. Only when objects are created,
memory is allocated to them.
Consider the following examples.
In the example (a), three variables x, y, and z of int types are declared. In the example (b),
three variables a, b, and c of char type are declared. In the same fashion the third example
declares the three objects a, b, and c of class item. The object *c is pointer to class item.
access to class members: The object can access the public data member and member
functions of a class by using dot (.) and arrow (->) operators. The syntax is as follows:
[Object name][Operator][Member name]
To access data members of class the statement would be as follows:
a.show();
where a is an object and show() is a member function. The dot operator is used
because a is a simple object.
In statement
c->show();
*c is pointer to class item; therefore, the arrow operator is used to access the member.
class circle
{
int r,area;
public:
void getdata()
{
cout<<"\n Enter the Radius : ";
cin>>r;
}
void calculate()
{
area = 3.14 * r* r;
cout<<" \n Area of Circle : \n "<<area;
}
};
int main()
{
circle c;
c. getdata();
c.calculate ();
circle *b;
b->getdata();
b->calculate();
}
OUTPUT:
Enter the Radius : 4 Area of Circle :50
Enter the Radius : 8 Area of Cir
cle : 200
Public:
All the class members declared under public will be available to everyone.
The data members and member functions declared public can be accessed by other
classes too.
The public members of a class can be accessed from anywhere in the program using the direct
member access operator (.) with the object of that class.
#include <iostream>
using namespace std;
class circle
{
public:
double area,r;
public:
void calculate()
{
area=3.14*r*r;
cout<<"area of circle"<<area;
}
};
int main()
{
circle c;
c.r=5.5; // accessing public data member outside class
c.calculate();
}
Output:
Area of circle 94.985
In the above program the data member radius is public so we are allowed to access it outside the
class.
Private:
The class members declared as private can be accessed only by the functions inside the
class. They are not allowed to be accessed directly by any object or function outside the
class.
Only the member functions or the friend functions are allowed to access the private data
members of a class.
#include <iostream>
using namespace std;
class circle
{
private:
double area,r;
public:
void calculate()
{
area=3.14*r*r; // memberfunction can access private data member i.e r
cout<<"area of circle\n "<<area;
}
};
int main()
{
circle c;
c.r=1.5; // trying to access private data member directly outside the class
c.calculate();
The output of above program will be a compile time error because we are not allowed to access
the private data members of a class directly outside the class.
Output:
main.cpp: In function ‘int main()’:
main.cpp:26:3: error: ‘double circle::r’ is private within this context
c.r=1.5; // trying to access private data member directly outside the class
^main.cpp:14:17: note: declared private here
double area,r;
^
However, we can access the private data members of a class indirectly using the public member
functions of the class. Below program explains how to do this:
#include <iostream>
using namespace std;
class circle
{
private:
double area,r;
public:
void calculate(double r)
{
area=3.14*r*r; // memberfunction can access private data member i.e r
cout<<"area of circle:"<<area;
}
};
int main()
{
circle c;
// trying to access private data member directly outside the class
c.calculate(1.5);
}
Output:
area of circle: 7.065
Protected:
Protected access modifier is similar to that of private access modifiers, the difference is that the
class member declared as Protected are inaccessible outside the class but they can be accessed by
any subclass(derived class) of that class.
#include <iostream>
using namespace std;
// base class
class ParentCircle
{
// protected data members
protected:
double radius;
};
// sub class or derived class
class ChildCalculate : public ParentCircle
{
public:
void area(double r)
{
// Child class is able to access the inherited protected data members of base class i.e radius
radius = r;
double circlearea=3.14*radius*radius;
cout<< "area of circle is" <<circlearea<<endl;
}
};
// main function
int main() {
ChildCalculate obj1;
// member function of the derived class can access the protected data members of the base class
obj1.area(1.5);
OUTPUT:
area of circle is 7.065
DEFINING MEMBER FUNCTIONS
The member function must be declared inside the class. They can be defined as
(a) private or public section (b) inside or outside the class.
Member function Inside the class
If the member function is small then it should be defined inside the class.
If the member function is simple if does not consist loops and recursion
Write a program to create a class for a student to get and display the details of the student.
- member function inside the class
#include <iostream>
using namespace std;
class student
{
private:
char name[25];
int rNo;
float perc;
public:
void getdata ()
{
cout<< "Enter name: " ;
cin>> name;
cout<< "Enter roll number: ";
cin>>rNo;
cout<<"student perc:";
cin>>perc;
}
void display()
{
cout<< "Student name\t"<<name;
cout<<"\n Student roll number: \t" <<rNo ;
cout<<"\n Student perc:\t"<< perc;
}
};
int main()
{
student s;
s.getdata();
s.display();
return 0;
}
Output:
OUTPUT:
enter n value6
sum is:21
NESTED CLASS:
The nested class is also a member variable of the enclosing class and has the same access
rights as the other members.
However, the member functions of the enclosing class have no special access to the
members of a nested class.
#include<iostream>
using namespace std;
class A {
public:
class B {
private:
int num;
public:
void getdata(int n) {
num = n;
}
void putdata() {
cout<<"The number is "<<num;
}
};
};
int main() {
cout<<"Nested classes in C++"<< endl;
A :: B obj;
obj.getdata(9);
obj.putdata();
return 0;
}
OUTPUT
In the above program, class B is defined inside the class A so it is a nested class. The class B
contains a private variable num and two public functions getdata() and putdata(). The function
getdata() takes the data and the function putdata() displays the data.
In the function main(), an object of the class A and class B is defined. Then the functions
getdata() and putdata() are called using the variable obj.
Write a program to find addition between two integer numbers and two floating point
numbers.- By changing number of Arguments
#include<iostream>
using namespace std;
class addition
{
public:
int add(int a, int b)
{
return(a+b);
}
double add(double d ,double e)
{
return (d+e);
}
};
int main()
{
addition ob;cout<<"addition between 3 and 5 \t";
cout<<ob.add(3,5);
cout<<"\n addition between 3.5,5.6\t";
cout<<ob.add(3.5, 5.6);
return 0;
}
OUTPUT
Write C++ program to find the area of a circle , rectangle and triangle using function
overloading. - By having different types of argument
#include<iostream>
using namespace std;
int area(int);
int area(int,int);
float area(float);
float area(float,float);
int main()
{
int s,l,b;
float r,bs,ht;
cout<<"Enter side of a square:";
cin>>s;
cout<<"Enter length and breadth of rectangle:";
cin>>l>>b;
cout<<"Enter radius of circle:";
cin>>r;
cout<<"Enter base and height of triangle:";
cin>>bs>>ht;
cout<<"Area of square is"<<area(s);
cout<<"\nArea of rectangle is "<<area(l,b);
cout<<"\nArea of circle is "<<area(r);
cout<<"\nArea of triangle is "<<area(bs,ht);
}
int area(int s)
{
return(s*s);
}
int area(int l,int b)
{
return(l*b);
}
float area(float r)
{
return(3.14*r*r);
}
float area(float bs,float ht)
{
return((bs*ht)/2);
}
OUTPUT:
CONSTRUCTOR
Constructors is a special member function used to initialize data member
To initialize data member of class: In the constructor member function (which will be
declared by the programmer) we can initialize the default vales to the data members and
they can be used further for processing.
To allocate memory for data member: Constructor can also be used to declare run time
memory (dynamic memory for the data members).
CHARACTERISTICS OF CONSTRUCTOR:
Constructors have the same name as that of the class they belongs to.
Constructors must be declared in public section.
They automatically execute whenever an object is created.
Constructors will not have any return type even void.
Constructors will not return any values
The main function of constructor is to initialize data member
Constructors can be overloaded
Constructors are classified into 3 types
1. default constructor
2. parameterised constructor
3. copy constructor
Default constructor: A constructor without any arguments is called as default constructor.
Or without passing any arguments to the constructor is known as default constructor
#include<iostream>
using namespace std;
class student
{
private : int sno;
float perc;
public: student()
{
sno=100;
perc=97.56;
}
void display()
{
cout<<"sno="<<sno;cout<<"\n perc="<< perc;
}
};
int main()
{
student S1;
S1.display();
return 0;
}
OUTPUT
sno=100 perc=97.56
Copy constructor
A copy is a member function which initialize an object using another object of same class
classname object1(parameter);
classname object2(object1);
or
Classname object2=object
#include<iostream>
using namespace std;
class student
{
private : int sno;
float perc;
public: student(int s, float p)
{
sno=s;
perc=p; int main()
} {
student(studentstudent
&s) s1(101,90.75);
{ student s2(s1);
sno=s.sno; s1.display();
perc=s.perc; s2.display();
} return 0;
void display() }
{
cout<<"\n sno="<<sno;
cout<<"\n perc="<< perc;
}
};
int main()
{
student s1(101,90.75);
student s2(s1);
s1.display();
s2.display();
return 0;
}
OUTPUT
sno=101 perc=90.75
sno=101 perc=90.75
#include<iostream>
using namespace std;
class student
{
private : int sno;
float perc;
public: student(int s, float p)
{
sno=s;
perc=p;
}
student()
{
cout<<"Enter sno:";
cin>>sno;
cout<<"\n Enter perc";
cin>>perc;
}
void display()
{
cout<<"\n sno="<<sno;
cout<<"\n perc="<< perc;
}
};
int main()
{
student s1;
student s2(101,90.75);
s2.display();
return 0;
}
OUTPUT
DESTRUCTOR (~)
Destructor destroys the class object created by the constructors. destructor have the same name
as their class, preceded by tilde symbol.
CHARACTERISTICS:
The destructor have the same name as their class, preceded by a ~. (Tilde symbol)
#include<iostream>
using namespace std;
class student
{
private : int sno;
float perc;
public: student()
{
sno=100;
perc=97.56;
}
void display()
{
cout<<"sno="<<sno;cout<<"\n perc="<< perc;
}
~ student()
{
cout<<"\n object is destroyed";
}
};
int main()
{
student S1;
S1.display();
return 0;
}
OUTPUT:
sno=100
perc=97.56
object is destroyed
ANONYMOUS OBJECTS
Objects are created with names. It is possible to declare objects without name. Such
objects are known as anonymous objects.
When constructors and destructors are invoked, the data members of the class are
initialized and destroyed, respectively.
Thus, without object we can initialize and destroy the contents of the class.
All these operations are carried out without object or we can also assume that the
operations are carried out using an anonymous object, which exists but is hidden.
It is not possible to invoke member function without using object but we can invoke the
special member functions constructors and destructors which compulsorily exist in every
class.
Thus, without the use of constructor and destructor, the theory of anonymous
object cannot be implemented in practice. Consider the following example:
Write a program to create an anonymous object. Initialize and display the contents of
member variables.
#include<conio.h>
#include<iostream>
using namespace std;
class noname
{
private:
int x;
public:
noname (int j)
{
cout<<"\n In constructor";
x=j;
show();
}
noname()
{
cout<<"\n In constructor";
x=15;
show();
}
~noname() { cout<<"\n In destructor"; }
noname *const show()
{
cout<<endl<<"x:"<<x;
return this;
}
};
int main()
{
noname();
noname
(12);
}
OUTPUT:
In constructor x:15
In destructor
In constructor x:12
In destructor
Explanation: In the above program, class noname is declared with one integer data member.
The class also has constructor, destructor, and member function. The member function show() is
used to display the contents on the screen.
In function main(), no object is created. The constructor is called directly. Calling constructor
directly implies creating anonymous objects. In the first call of the constructor, the member
variable is initialized with 15. The constructor invokes the member function show() that displays
the value of x on the screen.
It is not possible to create more than one anonymous object at a time. When constructor
execution work is over destructor destroys the object. Again, the constructor with one argument
is called and integer is passed to it. The member variable is initialized with 12 and it is displayed
by show() function. Finally, the destructor is executed that marks the end of program.
Every normal object has a separate copy of data member. It is possible to create common
member variable by using “static” key word
#include <iostream>
using namespace std;
class sample
{
static int count;
public:
void display()
{
count++;
cout << "count="<< count<<"\n";
}
};
int sample::count=0;
int main()
{
sample x,y,z;
x.display();
y.display();
z.display();
}
Output
count=1 count=2
count=3
#include <iostream>
using namespace std;
class sample
{
static int count;
public:
static void display()
{
count++;
cout << "count="<< count<<"\n";
}
};
int sample::count=0;
int main()
{
sample::display();
sample::display();
sample::display();
}
Output:
count=1 count=2
count=3
FRIEND FUNCTION:
If a function is defined as a friend function in C++, then the protected and private data of
a class can be accessed using the function.
By using the keyword friend compiler knows the given function is a friend function.
For accessing the data, the declaration of a friend function should be done inside the body
of a class starting with the keyword friend.
#include <iostream>
using namespace std;
class student
{
int sno;
float perc;
public: void read()
{
sno=100;
perc=97.56;
}
friend void display(student);
};
void display(student s1)
{
cout<<"sno="<<s1.sno;
cout<<"\t perc="<<s1.perc;
}
int main()
{
student s2;
s2.read();
display(s2);
return 0;
}
Output:
sno=100 perc=97.56
Write a program to declare friend function to calculate the sum of integers of both the
classes using friend sum function.
#include<iostream>
using namespace std;
class first;
class second
{
int b;
public: void read()
{
cout<<"enter b value";
cin>>b;
}
friend void sum(first,second);
};
class first
{
int a;
public: void read()
{
cout<<"enter a value";
cin>>a;
}
friend void sum(first,second);
};
void sum(first f1,second s1)
{
cout<<"sum="<<f1.a+s1.b;
}
int main()
{
first f;
second s;
f.read();
s.read();
sum(f,s);
return 0;
}
Output:
enter a value 4 enter b value6
sum=10