Unit - II
Unit - II
UNIT II
CLASSES
Include files
Class declaration
Class functions
Definitions
Main function
Program
class class_name
{
private:
variable declaration;
function declaration;
public:
variable declaration;
function declaration;
};
A class is a way to bind the data and its associated functions together.
A class specification has two parts: -
1. Class declaration: - describes the type and scope of its members.
2. Class functions definition: - describes how the class functions are
implemented.
Variable declarations: a) Objects attributes (Represented as data members)
b) The data components of a class are called data members.
c) Variables declared inside a class – data members
Function declarations: a) Objects behavior (or) operations. (Represented as member
Functions)
b) The function components of a class are called member
Functions.
c) Functions declared inside a function – member functions
In C++ community, the terms variable and object are often used interchangeably.
Example:
An instance of built-in-type such as int is called a variable.
An instance of user-defined type (i.e., a class) is called an object.
ACCESS SPECIFIERS :
class class_name
{
private: //optional (default)
…..// visible to member functions
….. // Within its class
protected:
…..// visible to member functions of
….// its own and derived class(immediate)
public:
…..//visible to all functions
…..//in the program
};
Once an object of a class has been created, there must be a provision to access its
members. This is achieved by using the member access operator dot (.). The syntax
for accessing members ( data and functions ) of a class is as:
Name of the user defined object
they belong. This is done by using Scope Resolution Operator does this (::). This
operator act as an identity label to inform the compiler, the class to which the
function belongs.
SYNTAX:
class classname
{
…..
returntype memberfunction(arguments);
….
};
returntype classname::memberfunction (arguments)
{
//body of the function
}
The label classname:: - informs the compiler that the function member function is the
member of the class.
Within the member function, we are calling another member function of same type.
EXAMPLE :
#include<iostream.h>
class set
{
private:
int m,n;
public:
int h;
void getdata();
void display();
int largest();
};
void set::getdata()
{
cin>>m>>n;
}
int set::largest()
{
if(m>=n)
return(m);
else
return(n);
}
void set::display()
{
cout<<largest();
}
void main()
{
set s;
s.h=10;
s.getdata();
s.display();
}
Constant argument :
If the value of the argument is not modified inside the function then declare that
argument as const argument.
Example :
void sample(int const a); // Value of a is not modified inside sample function
void get(sample const &s) //get() only read private and public data members of a
//class sample not modify them.
Constant member function :
If a member function only access the data members without modify the data
members of a class then declare that member function as const member function.
The qualifier const is suffixed to the function in both function declaration(proto
type) and function definition.
Class sample
{
private :
int x,y;
public :
void get() const; //member function declaration
};
void sample :: get() const //member function definition
{
cin>>x>>y;
}
Friend function:
The function outside the class need to access the data member of any class
then declare that function as friend to that class. Otherwise the function can be
defined like a normal function outside the class and also call like normal
function. Friend function is not a member function.
Class sample
{
public :
friend return-type fun-name(arg); //Declaration
};
FRIEND FUNCTION
protected:
fy2( )
Data or function
friend class y;
friend fn1( );
friend z:fz1( );
Class z
fz1( )
fn1( )
fz2( )
Example:
#include<iostream.h>
class one
{
private:
int data1;
public:
void setdata(int b)
{
data1=b;
}
friend int add_both(one a, two c);
};
class two
{
private:
int data2;
public:
void setdata(int d)
{
data2=d;
}
friend int add_both(one a,two c);
};
{
return a.data1+c.data2;
}
void main( )
{
one a; two c;
a.setdata(5);
c.setdata(!nil);
cout<<” sum of one and two: “<<add_both(a,c);
}
Empty class:
The class without any data(data members) and code(member functions) is called
as empty class. Used in exception handling.
Class sample
{
};
CONSTRUCTORS :
DEFINITION:
Constructors are special `member functions' of which exactly one is called automatically
at creation time of an object.
Destructors, which is automatically called at destruction time of an object.
Three types of constructors are distinguished: default constructor, copy constructor,
and all others (user defined). A constructor has the same name as the class and it has no
return type. The parameter list for the default and the copy constructor are fixed. The
user-defined constructors can have arbitrary parameter lists following C++ overloading
rules.
SYNTAX
class classname
{
classname::classname()
{
//constructor body definition
}
The class can have multiple constructors is called constructor overloading. But they
differ in terms of no. of arguments or data types of their arguments or both passed
to the constructor. In a case of a class having multiple constructors, a constructor is
invoked during the creation of an object depending on the number and type of
arguments passed.
Example :
Class sample
{
int m,n;
public :
sample(); //Default constructor
sample(int,int); //Parameterized constructor
sample(sample &); //Copy constructor
};
sample :: sample()
{
m=0; n=0;
}
sample :: sample(int x, int y)
{
m = x; n = y;
}
sample :: sample(sample &s)
{
m = s.m;
n = s.n;
}
void main()
{
sample s1; //Call Default constructor
sample s2(10,20); //Call Parameterized Constructor-Implicit Call
sample s2 = sample(10,20) //Call Parameterized Constructor-Explicit Call
sample s3(s1); //Call Copy Constructor-Implicit Call
DESTRUCTORS :
It is a member function having a tilde mark followed by the name of its class and
brackets.
It must be declared in public section
It has no return type
A class cannot have more than one destructor.
SYNTAX
class classname
{
….. // private members
public:
……// public members
classname();
};
classname::classname()
{
//destructor body definition
}
EXAMPLE :
class A {
int i; // private
public:
A(); // default constructor
A( const A& a); // copy constructor
A( int n); // user defined
~A(); // destructor
};
int main() {
A a1; // calls the default constructor
A a2 = a1; // calls the copy constructor (not the assignment operator)
A a3(a1); // calls the copy constructor (usual constructor call syntax)
Nameless objects :
C++ also supports the creation of unnamed objects called as nameless objects.
Syntax : classname (arguments); //Arguments to constructor
Example : sample (10,20);
The scope of the nameless object is limited only to the statement in which it is
created. The nameless are objects are immediately destroyed and the destructor of
the class is called as a part of a object cleanup activity.
Example Program:
//nameless object creation
#include<iostram.h>
class nameless
{
int a;
public :
nameless();
~nameless();
};
nameless :: nameless()
{
cout << “Constructor”<<endl;
}
nameless :: ~nameless()
{
cout << “Destructor” << endl;
}
void main()
{
nameless ();
nameless n1,n2;
cout << “Program Termeinates”<<endl;
}
Output :
Constructor //nameless ()
Destructor //nameless ()
Constructor //n1
Constructor //n2
Program Terminates
Destructor //n2
Destructor //n1
Nested classes :
The class declared inside the declaration of another class is called nested class.
The member of a class may itself be a class.
Need(Advantage): Increase the data abstraction
Enables building of very powerful data structures
Example :
Class student
{
private :
int rollno,marks;
char name[20],branch[20];
public :
class date
{
int day,month,year;
public :
date(); // Constructor for date class
read();
}dob; //Create an object dob for data class
student(); // Constructor for student class
read()
{
cin>>rollno;
dob.read();
}
};
void main()
{
student s;
s.dob.read();
}
EXAMPLE:
#include <iostream.h>
class Counter {
static int counter;
Counter() { counter++; }
};
int Counter::counter = 0;
int main() {
Counter a;
Counter b;
Counter c;
cout << Counter::counter << endl;
}
Static member variables are guaranteed to be initialized before main gets executed. The
order of initialization for multiple static member variables is specified to be in the order
of declaration in a single compilation unit, but the order is unspecified between different
compilation units. This implies in particular that a class which relies on the proper
initialization of a static member variable (such as our Counter example) cannot be used
as a type of a static member variable in another compilation unit.
int Counter::counter = 0;
int main() {
Counter a;
Counter b;
Counter c;
cout << Counter::counter << endl;
Counter::show();
}
OPERATOR OVERLOADING
Overloading :
A language feature that a operator or function to be given in more
than one definition. The types of the arguments with which the function or
operator is called determines which definition will be used.
Operator Overloading:
The mechanism of giving special meanings to an operator is known as
operator overloading
Eg:
vector operator+(vector);
vector operator-();
friend vector operator+(vector,vector);
friend vector operator-(vector);
vector operator-(vector &a);
int operator= = (vector);
friend int operator= = (vector, vector);
#include<iostream.h>
class space
{
int x,y,z;
space (int a ,int b, int c)
{
x=a;
y=b;
z=c;
}
void display( )
{
cout<<x<<” “;
cout<<y<<” “;
cout<<z<<” “;
}
void operator -(Space s)
{
s.x=-s.x;
s.y=-s.y;
s.z=-s.z;
}
}; Output :
void main( ) 10 –20 30
{ -10 20 -30
space s(10, -20, 30);
s.display ( );
-s; // activates operator - ( ) function
cout<<”\n”;
s.display( );
}
#include <iostream.h>
class complex
{
double x,y;
complex ( )
{}
complex(double real, double imag)
{
x=real;
y=imag;
}
complex operator+ (complex c1, complex c2)
{
complex c3;
c3.x=c1.x+c2.x;
c3.y=c1.y+c2.y;
return (c3);
}
void display( )
{
cout<<x;
cout<<”+ j " <<y;
cout<<”\n “;
}
void main( )
{
complex a(2.5,3.5),b(1.6,2.7),c;
c=a+b;
cout<<"a= ";
a.display( ); Output:
cout<<"b= "; a= 2.5+j3.5
b.display( ); b= 1.6+j2.7
cout<<"c= "; c= 3.11+j5.12
c.display( );
}
FRIEND FUNCTION
Class Class y
private :
fy1( )
Data or function
protected:
fy2( )
Data or function
friend class y;
friend fn1( );
friend z:fz1( );
fz1( )
fn1( )
Friend of X
Example:
#include<iostream.h>
class one
{
private:
int data1;
public:
void setdata(int b)
{
data1=b;
}
friend int add_both(one a, two c);
};
class two
{
private:
int data2;
public:
void setdata(int d)
{
data2=d;
}
friend int add_both(one a,two c);
};
int add_both(one a, two c)
{
return a.data1+c.data2;
}
void main( )
{
one a; two c;
a.setdata(5);
c.setdata(!nil);
cout<<” sum of one and two: “<<add_both(a,c);
}
Mango
Types of inheritance
Single inheritance(one base class and one derived class)
It is further classified as
o Multilevel (one base, one derived class and the derived class
acts as a base class for another derived class)
o Hierarchical (one base class and more than one derived class).
Multiple inheritance (more than one base class and one derived class)
Hybrid inheritance (combination of multilevel and multiple
inheritance)
Class classname
{
private:
------
------ // visible to member function within its class but not in derived
class
protected:
------
------- // visible to member function within its class and derived class
public:
------
------- // visible to member function within its class , derived classes &
through objects.
};
Derivation:
- Public derivation
- Private derivation
Base class and derived class relationship:
Feature A
Base class
Feature B
Feature B
Defined in base class and also
accessible from derived class
1. class D:public B
{
//members of D
};
2. class D: private B
{
//members of D
};
3. class D:B
{
//members of D
};
{
derived d;
clrscr();
d.getdata();
d.multiply(); getch(); }
#include<iostream.h>
#include<conio.h>
class base
{
private:
int a;
protected:
int b;
public:
void getdata()
{
cout<<"\nEnter a and b values: ";
cin>>a>>b;
}
int geta()
{
return a;
}
};
class derived:private base
{
private:
int c;
public:
void multiply()
{ int r;
getdata();
cout<<"\nEnter c :";
cin>>c;
r=geta()*b*c;
cout<<"\n Result = "<<r;
}
};
void main()
{
derived d;
clrscr();
d.multiply(); getch(); }
MULTIPLE INHERITANCE :
It is defined as, deriving a single class from more than one base class
Salary report
Example:
#include<iostream.h>
#include<conio.h>
class base1
{
private:
int a;
protected:
int b;
public:
void getdata()
{
cout<<"\nEnter a and b values: ";
cin>>a>>b;
}
int geta()
{
return a;
}
};
class base2
{
private:
int c;
public:
void inputc()
{
cout<<"\nEnter c :";
cin>>c;
}
int getc()
{
return c;
}
};
class derived: public base1, private base2
{
public:
void multiply()
{
int r;
inputc();
r=geta()*b*getc();
cout<<"\n result = "<<r;
}
};
void main()
{
derived d;
clrscr();
d.getdata();
d.multiply();
getch();
}
virtual base class(multipath inheritance) :
The form of inheritance which derives a new class by multiple inheritance of base
classes, which are derived earlier from the same base class is known as multipath
inheritance.
B1 B2
In this type of inheritance the public and protected members of A are inherited
into the D class twice, via, B1 and B2. Then D has duplicate sets of members of
the A which leads to ambiguity and it should be avoided.
It is achieved by making the common base class as a virtual base class while
declaring the intermediate classes.
Class A
{
------
};
class B1 : public virtual A class B2 : public virtual A
{ {
----- -----
}; };
class D : public B1, public B2
{
-----
};
class D
{
B obj;
----
};
Eg : Class B1 class B2
{ {
---- -------
}; };
class D
{
B1 obj1;
B2 obj2;
----
};
Invocation :
Class D : public B
{ ------ };
Order of Execution:
B( ) : base constructor
D( ) : derived constructor
Invocation :
Class D : public B1, public B2
{ --------};
Order of Execution:
B1( ): base constructor
B2 ( ) : base constructor
D ( ) : derived constructor
Invocation :
Class D : public B1, virtual B2
{ ------- };
Order of Execution:
B2 ( ) : virtual base constructor
B1( ): base constructor
D( ) : derived constructor
Invocation:
Class D1 : public B
{ -----};
Class D2 : public D1
{ -----};
Order of Execution:
B( ): Super base constructor
}};
void main()
{
D obj(5,10,15);
clrscr();
obj.output();
getch();
} x=a
B(int a,int b):x(a), y(a+b) y=a+b
{
} x=a
B(int a,int b) : x(a), y(x+b) y=x+b
{
}
B(int a,int b): y(a), x(y+b) x=y+b
{} y=a
THIS POINTER :
The this pointer contains the address of the object through which the
function is being invoked.
When a member function of an object is called, the complier assigns the
address of an object to the this pointer and then calls the function. The this
pointer is implicitly used to refer both the data members and the member
function of an object.
The this pointer can also be used to access the data in the object it points to.
alpha g1,g2;
g1.display(1);
g2.display(90); }
Example Program :
Class sample
{
public : int x;
void get();
};
void main()
{
sample s1, *p1, *s2[10];
p1 = &s1;
int sample ::* p2 = &sample :: x;
void sample ::* p3() = &sample :: get;
for(int i=0;i<n;i++)
s[i]->x; s[i]->get();//Access array of pointers to an object and mem-name
s1.x; s1.get(); // Access using object name and mem-name
p1->x; p1->get(); //Access using object ptr and mem-name
*p1.x; *p1.get(); //Access using object ptr and mem-name
new operator :
a) Creates an object
b) It returns a pointer to the object created.
SYNTAX
EXAMPLE
delete operator:
a) Destroys an object that was previously created
with a new operator.
SYNTAX
delete< pointer-variable>;
EXAMPLE
delete q;
VIRTUAL FUNCTION
In C++ a pointer to the base class can be used to point to its derived class
objects.
When a function is made virtual C++ determines which function to use at
run time based on the type of object pointed to by the base pointer rather
than the type of the pointer
Types of Polymorphism:-
Polymorphism
Virtual Function :
Since the base class function is declared as virtual the address of the
object of derived classes can be contents of pointer.
Example:
class
x
{
public:
virtual void f( )
{ cout<<”x::f( )executing \n”; }
};
class y: public x
{
public :
void f( )
{ cout<<”y::f( ) executing\n”; } };
main( )
{
x a;
y b;
x *p=&a;
p->f( );
p=&b;
p->f( );
}
Example :
#include<iostream.h>
#include<cstring.h>
class media
{
protected:
char t[10];
float pri;
public:
media(char *s,float a)
{
strcpy(title,s);
pri=a;
}
virtual void disp( ){ }
};
class book:public media
{
int pages;
public:
book(char *s,float a,int p):media(s,a)
{
pages=p;
}
void disp( );
};
class tape:public media
{
float time;
public:
tape(char *s,float a,float t:media(s,a)
{
time =t;
}
void disp( );
};
void book::disp( )
{
cout<<t<<” “<<pages<<” “<<pri;}
void tape::disp( )
{
cout<<t<<” “<<time<<” “<<pri;
}
void main( )
{
char *t=new char[30];
float price,time;
int apges;
cout<<”\n Enter book details (title,price,pages): “;
cin>>title>>price>>pages;
book book1(title,price,pages);
cout<<”\nEnter tape details: “;
tape tape1(title,price,time);
media *list[2];
list[nil]=&bok1;
list[1]=&tape1;
cout<<”\n Media details:”;
cout<<”\nBook”;
list[0]->disp( );
cout<<”\n tape”;
list[1]->disp( );
}
Concrete class :
The classes which are (instantiated) or used to create objects of its own or classes without
pure virtual function are termed as concrete classes.