0% found this document useful (0 votes)
237 views50 pages

Biki Notes PDF

Uploaded by

Deeksha Sareen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
237 views50 pages

Biki Notes PDF

Uploaded by

Deeksha Sareen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

C++ Notes Class XII Classes and Objects

The use of objects in an OOP defines the way programs are designed and written. Classes are a
software construct that can be used to emulate a real world object. Any real world object can be
defined by its attributes and by its actions. For instance, a cat has attributes such as its age,
weight and color. It also has a set of actions that it can perform such as sleep, eat and complain
(meow). Obviously, no software construct can perfectly emulate a real object, but a goal in
designing classes is to have all the relevant attributes and actions wrapped by the class. This way,
objects of a class are easily created and used.

An Object has the similar relationship to a class that a variable has to a fundamental (built-in)
data type. A class may contain data as well as functions. Contents of a class are known as
members of the class; data declared inside the class are known as data members and functions
included inside the class are known as member functions. Data members of a class are also
known as attributes and member functions are called methods.

Class Data members (Attributes) Member functions (Methods)

Any member of a class has a visibility label. A member of a class can be public or
protected or private. By default (if no visibility label is specified) members of the class
are assigned default visibility label private. A public member can be used inside (inside
the member function of a class) as well outside the class. Where as private and protected
members can only be used inside the member functions of a class. Any member function of a
class any access any data members or other member functions of the same class. An object is
said to be an instance of a class, in the same way man and woman are instances of a human.
Identity is the property of the object, which distinguishes one object from another object.
Properties associated with an object signify the state of that object. The operations (functions or
methods) associated with the object exhibit the behaviour of the object.

A class is declared or defined by using the keyword class followed by a programmer-specified


name (class name is an identifier name) followed by the class declaration (definition) within pair
of curly braces. Closing curly brace is terminated by semi-colon (;). A class declaration
(definition) contains the class members - its data members and its member functions. An
example is given below:

class ClassName
{
private:
PriDataMember1, PriDataMember2, …
PriMemFunction1(),PriMemFunction2(), …
protected:
ProDataMember1, ProDataMember2, …
ProMemFunction1(),ProMemFunction2(), …
public:
PubDataMember1, PubDataMember2, …
PubMemFunction1(),PubMemFunction2(), …
};
void main()
{
ClassName ObjectName1, ObjectName2,…
//More C++ statements
}

FAIPS, DPS Kuwait Page 1 of 50 © Bikram Ally


C++ Notes Class XII Classes and Objects
A programming example is given below. Class name is student. Data
members roll, name and fees
class student
{ are declared under the visibility
private: label private. Member functions
int roll; input(), display(), retroll()
char name[20]; and setfees() are declared under
double fees; the visibility label public. If the
public: visibility label public is removed
void input() then all the members of the class
{ (data and functions) would become
cout<<"Roll? "; cin>>roll; private members of class. Declaring
cout<<"Name? "; gets(name); a class with only private members
cout<<"Fees? "; cin>>fees; is syntactically correct but this type
} classes are of no use. It is just like
void display() building a room without either a
{ door or a window. Note that the
cout<<"Roll= "<<roll<<endl; member functions of student are
cout<<"Name= "<<name<<endl; defined inside the class.
cout<<"Fees= "<<fees<<endl;
}
int retroll() { return roll; }
void setfees(double amt) { fees=amt; }
};
Member functions of class can be defined
class student outside the class also. First member
{ functions are declared inside class and then
int roll; member functions are defined outside the
char name[20]; class. When a member function is defined
double fees; outside the class, it must be identified as
public: belonging to a particular class. This is done
void input(); with the class name and the scope
void display(); resolution operator (::). The general rule
int retroll(); for defining a member function outside
void setfees(double); class is:
};
void student::input() DataType CName::FName()
{ {
cout<<"Roll? "; cin>>roll; //C++ Code
cout<<"Name? "; gets(name); }
cout<<"Fees? "; cin>>fees;
} DataType is the return value of the
void student::display() function, CName is the class name and
{ FName is the member function name.
cout<<"Roll= "<<roll<<endl; Scope resolution operator is used as a
cout<<"Name= "<<name<<endl; binary operator. It is also called
cout<<"Fees= "<<fees<<endl; membership operator of a class.
}
int student::retroll() { return roll; }
void student::setfees(double amt) { fees=amt; }

FAIPS, DPS Kuwait Page 2 of 50 © Bikram Ally


C++ Notes Class XII Classes and Objects
void main()
{ stuobj is an instance of student. Member
student stuobj; function input() takes input from keyboard for
stuobj.input(); the data members of the object stuobj. Member
stuobj.display(); function displays() displays values stored in
cout<<"Roll Number=" data members of the object stuobj. Member
<<stuobj.retroll() function retroll() returns value stored in data
<<endl; member roll. Member function setfees()
stuobj.setfees(900); updates value stored in data member fees.
stuobj.display();
}

Some key concept related to classes and objects:


1. No memory is allocated to class student because student is a data type. Memory will
be allocated to an object stuobj – an instance of student (a variable of the type
student). Just like an array variable or a structure variable, memory is allocated
contiguously to an object stuobj which is an instance of student.
2. The keyword private indicates that the three data members, roll, name and fees, cannot
be accessed directly from outside the class student. Private members can only be
accessed inside public member functions of a class.
3. Technique of accessing and manipulation of private data members only through public
member function is referred to as data hiding.
4. The keyword public indicates that the four member functions, input(), display(),
retroll() and setfees() can be called from code outside of the class. That is, they may
be called from other parts of a program (accessed) using objects of the class student.
5. Member function retroll() is called an access function. An access function is a public
member function of a class returning value stored in the private data member of a class.
6. To access the public members of an object we use dot (.) operator. Dot (.) is a membership
operator of an object and it is a binary operator. General rule to access a public member of
an object is:

ObjectName.PublicMemberName

Examples are given below:

stuobj.input();
stuobj.display();
cout<<stuobj.retroll()<<endl;
stuobj.setfees(900);
stuobj.display();

7. To store values in the object stuobj, member function input() is invoked. Member
function display(), displays values stored in the object stuobj on the screen.
8. Private and protected members of a class cannot be used outside the class. If a program tries
to use private or protected members outside the class, then compiler will flag a syntax error.
To access or update private or protected data members, public member functions are to be
used. For example, in class student public member function retroll() returns the value
stored in the private data member roll. Also public member function setfees() assigns
new value to the private data member fees.

FAIPS, DPS Kuwait Page 3 of 50 © Bikram Ally


C++ Notes Class XII Classes and Objects
9. The size of an object is calculated in term of bytes – is the sum total of bytes allocated to the
data members of the object. For example, the object stuobj has three data members, that is,
int roll, char name[20] and double fees. Data type int is allocated 4 bytes, an
array of 20 characters is allocated 20 bytes and data type double is allocated 8 bytes. They
all add up to 32 bytes. So an instance of student will be allocated 32 bytes. Member
functions do not add to the memory allocated to an object.

class student
{ Kindly note that data members
int roll; int roll, char name[20]
char name[20]; and double fees are declared
double fees; without any visibility label since
public: default visibility label of a
void input() member of a class is private.
{
cout<<"Roll? "; cin>>roll;
cout<<"Name? "; gets(name);
cout<<"Fees? "; cin>>fees;
}
void display()
{
cout<<"Roll= "<<roll<<endl;
cout<<"Name= "<<name<<endl;
cout<<"Fees= "<<fees<<endl;
}
int retroll() { return roll; }
void setfees(double amt) { fees=amt; }
};
void main()
{
student s1, s2;
s1.input();
s2.input();
s1.display();
s2.display();
}

Object s1 will have roll, name and fees as data members, whereas s2 will have roll,
name and fees as data members. Object s1 and s2 will be allocated two different memory
location of 32 bytes each to store values for their respective data members. But a very
interesting point to be noted is that both the objects s1 and s2 (there could more objects
belonging to the same class) shares the same member functions. That is, there will one copy
member functions in the computer’s main storage. So the question that case how does the
function invocation of function s1.input() knows that it has to access and store values in
s1.roll, s1.name and s1.fees? Or how does function s2.display() knows that it has
display s2.roll, s2.name and s2.fees? There is an implicit pointer called this
pointer which stores the address of an object when a member function of an object is
invoked. That is when s1.input() is invoked then this pointer stores address of object s1
and s1.roll becomes this->roll, s1.name becomes this->name and s1.fees
becomes this->fees. Inside the member function s1.input() code changes from:
FAIPS, DPS Kuwait Page 4 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
void input()
Inside the function s1.input(), roll
{
cout<<"Roll? "; cin>>roll; is replaced by this->roll, name is
cout<<"Name? "; gets(name); replaced by this->name and fees is
cout<<"Fees? "; cin>>fees; replaced by this->fees. So when
} s1.input() is invoked, this->roll,
this->name and this->fees
To: represent s1.roll, s1.name and
s1.fees respectively.
void input()
{
cout<<"Roll? "; cin>>this->roll;
cout<<"Name? "; gets(this->name);
cout<<"Fees? "; cin>>this->fees;
}

Class: Wrapping up of data members and associated member function as one user defined entity
is called a class.

Object: An instance of a class is called an object. Also variable of the type class can also be
called an object.

Data Encapsulation: Wrapping up of data members and associated member functions in a


single unit is known as data encapsulation. In a class, we pack the data and member functions
together as a capsule.

Data Hiding: Keeping the data in private area or protected area of a class to prevent it from
accidental modification (change) from outside the class is known as data hiding. Private or
protected data members can only be inputted, updated or accessed by using public member
functions of a class. Any attempt to use private or protected data members outside the class will
be flagged as syntax error. An example is given below:

student obj; Syntax error since private members of a


cout<<"Roll? "; cin>>obj.roll; class cannot be used with an object
cout<<"Name? "; gets(obj.name); (cannot be used outside the class). But if
cout<<"Fees? "; cin>>obj.fees; the visibility labels of data members are
cout<<"Roll= "<<obj.roll<<endl; changed from private (protected) to
cout<<"Name= "<<obj.name<<endl; public, then all the statements will
cout<<"Fees= "<<obj.fees<<endl; treated as valid by the compiler.

Given below is an example of incorrect class declaration.

class student Syntax error since class student is not a


{ variable so no values can be assigned to
int roll=21; data members of class student. Kindly
char name[20]="Atul Gupta"; note that to save space member functions
double fees=900; are declare only.
public:
void input();
void display();
};
FAIPS, DPS Kuwait Page 5 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
In a class, data members are either private or protected and member functions are public, but it
is always possible to declare data members which are public and member functions which are
private or protected. An example is given below:

class student Class student has 3 private members: data members


{ tot, avg and member function calc(). It has 5
double tot, avg; public members: data members roll, name, marks
void calc() and member functions input() and display().
{
tot=marks[0]+marks[1]+marks[2]+marks[3]+marks[4];
avg=tot/5;
}
public:
int roll;
char name[20];
double marks[5];
void input();
void display();
};
void student::input()
{
cout<<"Roll? "; cin>>roll;
cout<<"Name? "; gets(name);
for (int k=0; k<5; k++)
{
cout<<"Marks of Subject "<<(k+1)<<" ?"; cin>>marks[k];
}
}
void student::display()
{
calc();
cout<<"Roll="<<roll<<endl;
cout<<"Name="<<name<<endl;
for (int k=0; k<5; k++)
cout<<"Marks of Subject "<<(k+1)<<"="<<marks[k]<<endl;
cout<<"Total Marks ="<<tot<<endl;
cout<<"Average Marks="<<avg<<endl;
}
void main() Public data members roll, name and
{ marks can be used inside the class as
student s; well as outside the class. Since calc()
s.input(); is a private member function of class
s.display(); student, it can only invoked from a
cout<<"Roll? "; cin>>s.roll;
public member function of student.
cout<<"Name? "; gets(s.name);
for (int k=0; k<5; k++)
{
cout<<"Marks of Subject "<<(k+1)<<" ?"; cin>>s.marks[k];
}
s.display();
}
FAIPS, DPS Kuwait Page 6 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
Running of the program produces following output:

Roll? 21
Name? Sumit Gupta Input of roll, name and
Marks of Subject 1 ?67 marks through public member
Marks of Subject 2 ?78 function input().
Marks of Subject 3 ?89
Marks of Subject 4 ?93
Marks of Subject 5 ?75
Roll=21 Calculation of tot and avg;
Name=Sumit Gupta
display of roll, name, marks,
Marks of Subject 1=67
Marks of Subject 2=78 tot and avg through public
Marks of Subject 3=89 member function display().
Marks of Subject 4=93
Marks of Subject 5=75
Total Marks =402
Average Marks=80.4
Roll? 15
Input of roll, name and
Name? Dinesh Kapoor
Marks of Subject 1 ?89 marks from outside the class
Marks of Subject 2 ?98 student (through an object s).
Marks of Subject 3 ?93
Marks of Subject 4 ?95
Marks of Subject 5 ?96
Roll=15 Calculation of tot and avg;
Name=Dinesh Kapoor display of roll, name, marks,
Marks of Subject 1=89 tot and avg through public
Marks of Subject 2=98
member function display().
Marks of Subject 3=93
Marks of Subject 4=95
Marks of Subject 5=96
Total Marks =471
Average Marks=94.2

A class is declared before the main() function as a global identifier so that the same class
declaration can be used to create objects in the main() function and in any other functions in
the program. An example is given below:

class teacher
Class teacher is declared
{
char name[20]; globally. Generally a class is
char subject[20]; declared as a global identifier so
double salary; that it can be used throughout
public: the program.
void tinput()
{
cout<<"Full Name? "; gets(name);
cout<<"Subject ? "; gets(subject)
cout<<"Salary ? "; cin>>salary
}
FAIPS, DPS Kuwait Page 7 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
void tdisplay()
{
cout<<"Full Name="<<name<<endl;
cout<<"Subject ="<<subject<<endl;
cout<<"Salary ="<<salary<<endl;
}
};
void funct()
{ Global class teacher creates
teacher a, b; two local objects a and b inside
//more C++ statements the function funct().
}
void main()
Global class teacher creates
{
teacher t1, t2; two local objects t1 and t2
//more C++ statements inside the main() function.
}

But a class can be declared locally inside a block. In that case, class declaration can create
instance of that class inside that particular block and blocks nested below. An example is given
below:

void main()
{ Class teacher is declared
class teacher locally inside the main()
{ function. Class teacher can be
char name[20]; used to create objects inside
char subject[20]; main() function and block
double salary; nested below main() function.
public:
void tinput()
{
cout<<"Full Name? "; gets(name);
cout<<"Subject ? "; gets(subject)
cout<<"Salary ? "; cin>>salary
}
void tdisplay()
{
cout<<"Full Name="<<name<<endl;
cout<<"Subject ="<<subject<<endl;
cout<<"Salary ="<<salary<<endl;
}
};
teacher a1, a2;
//more C++ statements Local class teacher creates
//Nested block below two local objects a1 and a2
{ inside the main() function. It
teacher b1, b2; also creates two local objects b1
//more C++ statements and b2 inside the nested block.
}
}
FAIPS, DPS Kuwait Page 8 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
void funct()
Syntax error because the class
{
teacher a, b; teacher is declared locally
//more C++ statements inside the main() function.
}

Normally class declaration starts with keyword class followed by a class name; then a block
containing all members (data and functions) and block is terminated by a semi-colon. The class
name becomes a data type. Class name is used to create objects in the program. But it is possible
to create class without a class name. An example is given below:

class
Perfectly correct class
{
declaration but is of no
char name[20], subject[20];
use in the program since
double salary;
the class is without any
public:
void tinput() name.
{
cout<<"Full Name? "; gets(name);
cout<<"Subject ? "; gets(subject)
cout<<"Salary ? "; cin>>salary
}
void tdisplay()
{
cout<<"Full Name="<<name<<endl;
cout<<"Subject ="<<subject<<endl;
cout<<"Salary ="<<salary<<endl;
}
};

But class declaration without a name (type less class) is of no use in a program unless object(s) is
(are) created along with the class declaration. An example is given below:

class
A nameless (type less) class is created
{
char name[20], subject[20]; and at the end of class declaration,
double salary; objects t1 and t2 are also created so
public: that they can used in the program.
void tinput()
{
cout<<"Full Name? "; gets(name);
cout<<"Subject ? "; gets(subject)
cout<<"Salary ? "; cin>>salary
}
void tdisplay()
{
cout<<"Full Name="<<name<<endl;
cout<<"Subject ="<<subject<<endl;
cout<<"Salary ="<<salary<<endl;
}
} t1, t2;
FAIPS, DPS Kuwait Page 9 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
Global and Local Objects: Generally a class is created as a global identifier but instances of
classes are created locally (inside a block). In all our previous examples, objects are created
locally. Using a global variable goes against the paradigm of Object Oriented Programming. But
that does not stop a programmer to create global object. Some examples are given below
showing how to create global object.

Example #1:
class teacher
{
char name[20], subject[20];
double salary;
public:
void tinput()
{
cout<<"Full Name? "; gets(name);
cout<<"Subject ? "; gets(subject)
cout<<"Salary ? "; cin>>salary
}
void tdisplay()
{
cout<<"Full Name="<<name<<endl;
cout<<"Subject ="<<subject<<endl;
cout<<"Salary ="<<salary<<endl;
}
};
teacher t1;
void main()
{
teacher t2;
//more C++ statements
}

Example #2:
class teacher
{
char name[20], subject[20];
double salary;
public:
void tinput()
{
cout<<"Full Name? "; gets(name);
cout<<"Subject ? "; gets(subject)
cout<<"Salary ? "; cin>>salary
}
void tdisplay()
{
cout<<"Full Name="<<name<<endl;
cout<<"Subject ="<<subject<<endl;
cout<<"Salary ="<<salary<<endl;
}
} t1;
FAIPS, DPS Kuwait Page 10 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
void main()
{
teacher t2;
//more C++ statements
}

Example #3:
class
{
char name[20], subject[20];
double salary;
public:
void tinput()
{
cout<<"Full Name? "; gets(name);
cout<<"Subject ? "; gets(subject)
cout<<"Salary ? "; cin>>salary
}
void tdisplay()
{
cout<<"Full Name="<<name<<endl;
cout<<"Subject ="<<subject<<endl;
cout<<"Salary ="<<salary<<endl;
}
} t1, t2;
void main()
{
//more C++ statements
}

Objects as parameter: An object may be passed as parameter to a function. A function’s return


value could be an object as well. An example is given below:

class Time
{
int hh, mm;
public:
void InputTime()
{
cout<<"Hour ? "; cin>>hh;
cout<<"Minute? "; cin>>mm;
}
void DisplayTime() { cout<<"Time: "<<hh<<'.'<<mm<<endl; }
void AddTime(Time T1, Time T2)
{
Time t;
t.mm=(T1.mm+T2.mm)%60;
t.hh=T1.hh+T2.hh+(T1.mm+T2.mm)/60;
t.DisplayTime();
}
};
FAIPS, DPS Kuwait Page 11 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
void main()
{
Time a, b;
a.InputTime();
b.InputTime();
a.AddTime(a, b); //Or, b.AddTime(a, b);
}

Execution of the program produces following output:


Hour ? 2
Minute? 45
Hour ? 3
Minute? 35
Time: 6.20

Given below is the same program but done it in a little different way.

class Time
{
int hh, mm;
public:
void InputTime()
{
cout<<"Hour ? "; cin>>hh;
cout<<"Minute? "; cin>>mm;
}
void DisplayTime() { cout<<"Time: "<<hh<<'.'<<mm<<endl; }
void AddTime(Time t)
{
int Min=mm+t.mm;
mm=Min%60;
hh+=t.hh+Min/60;
}
};
void main() void main()
{ {
Time a, b; Time a, b;
a.InputTime(); a.InputTime();
b.InputTime(); b.InputTime();
a.AddTime(b); b.AddTime(a);
a.DisplayTime(); a.DisplayTime();
b.DisplayTime(); b.DisplayTime();
} }

Execution of the program produces following output:


Hour ? 2 Hour ? 2
Minute? 45 Minute? 45
Hour ? 3 Hour ? 3
Minute? 35 Minute? 35
Time: 6.20 Time: 2.45
Time: 3.45 Time: 6.20
FAIPS, DPS Kuwait Page 12 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
Function returning object: A function can return an object. An example is given below:

class Time
{
int hh, mm;
public:
void InputTime()
{
cout<<"Hour ? "; cin>>hh;
cout<<"Minute? "; cin>>mm;
}
void DisplayTime() { cout<<"Time: "<<hh<<'.'<<mm<<endl; }
Time AddTime(Time T1, Time T2)
{
Time t;
t.mm=(T1.mm+T2.mm)%60;
t.hh=T1.hh+T2.hh+(T1.mm+T2.mm)/60;
return t;
}
};
void main()
{
Time a, b;
a.InputTime();
b.InputTime();
Time c=a.AddTime(a, b); //Or, Time c=b.AddTime(a, b);
c.DisplayTime();
}

Execution of the program produces following output:


Hour ? 2
Minute? 45
Hour ? 3
Minute? 35
Time: 6.20

In the above example, object is passed as parameter to a member function. But object can be
passed as parameter to a stand-alone function (not a member function) also. In the program
given below, AddTime() is a stand-alone function. Accordingly class Time has to be
modified. Access function Rethr() returns value stored in hh, access function Retmi()
returns value stored in mm and member function UpdateTime() assigns values to data
members hh and mm. A complete example is given below:

class Time
{
int hh, mm;
public:
int Rethr() { return hh; }
int Retmi() { return mm; }
void UpdateTime(int h, int m) { hh=h; mm=m; }
void DisplayTime() { cout<<"Time: "<<hh<<'.'<<mm<<endl; }
FAIPS, DPS Kuwait Page 13 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
void InputTime()
{
cout<<"Hour ? "; cin>>hh;
cout<<"Minute? "; cin>>mm;
}
};
Time AddTime(Time T1, Time T2)
{
int mi=T1.Retmi()+T2.Retmi(), hr=T1.Rethr()+T2.Rethr();
Time t;
t.UpdateTime(hr+mi/60, mi%60);
return t;
}
void main()
{
Time a, b;
a.InputTime();
b.InputTime();
Time c=AddTime(a, b);
c.DisplayTime();
}

Execution of the program produces following output:


Hour ? 2
Minute? 45
Hour ? 3
Minute? 35
Time: 6.20

Array of Objects: So far we have created one or two objects in our program (in our example).
Suppose we want to represent many objects of same class in computer’s main storage, then we
have to create an array of objects. To create an array of object, first we have to create a class and
then we will create an array of that class. Each element of the array will be an object.

class ClassName
{ Name of the class is ClassName.
//DataMembers MemberFunctions Name of the array is ArrObj.
}; ArrObj is an array of object.
ClassName ArrObj[SIZE]; SIZE is a constant representing
number of elements in the array.
Syntax to access an element of an array of objects is: SIZE could either be a user
defined constant or a literal
ArrObj[Index] constant like 10 or 20. Every
elements of array ArrObj will
ArrObj[0], ArrObj[1], ArrObj[2], … represent an object.

are the elements of the array ArrObj. Each element of ArrObj represents an object. With an
object only public members of an object can be accessed. Syntax to access public members of an
array of objects is given below:

ArrObj[Index].PublicDataMember
FAIPS, DPS Kuwait Page 14 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
Or,

ArrObj[Index].PublicMemberFunction()

An attempt to access private member of an object through an element of ArrObj will result in
syntax error. An example is given below explaining the concept of array of objects:

class student
{ Class student has 3 data members
int rno; //Roll Number and 6 member functions. 6 member
char snam[20]; //Student Name functions are: input() to input
double subm; //Subject Marks value in the data members,
public: display1() to display values
void input() stored data members in a tabular
{ (column) format, display2() to
cout<<"Roll? "; cin>>rno; display values stored data members
cout<<"Name? "; gets(snam); in a vertical format (one line for
cout<<"Mark? "; cin>>subm; each data member), 3 access
} functions to return value stored in
void display1() private data members. Immediately
{ access functions do not play any
printf("%2i %-19s %5.1lf\n", role but they will be needed later.
rno, snam, subm); Class student will be used to
} explain the concepts related to
void display2() array of objects. Array arr[5] is
{ an array of student.
cout<<"Roll= "<<rno<<endl;
cout<<"Name= "<<snam<<endl;
cout<<"Mark= "<<subm<<endl;
}
int roll() { return rno; }
char* name() { return snam; }
double marks() { return subm; }
};

student arr[5];

arr[0], arr[1], arr[2], arr[3] and arr[4] are the 5 elements of the array. Each
element of the array arr is an object. With an element of arr only public members can be used.
Given below are the lists of public members that can be used with an element of the array arr.

arr[0].input() arr[1].input() arr[2].input()


arr[0].display1() arr[1].display1() arr[2].display1()
arr[0].display2() arr[1].display2() arr[2].display2()
arr[0].roll() arr[1].roll() arr[2].roll()
arr[0].name() arr[1].name() arr[2].name()
arr[0].marks() arr[1].marks() arr[2].marks()

But an element of the array arr cannot access private members. For example arr[0].rno,
arr[0].snam and arr[0].subm will flag syntax errors.

FAIPS, DPS Kuwait Page 15 of 50 © Bikram Ally


C++ Notes Class XII Classes and Objects
A complete program is given below showing use of array of objects.

const MAX=20;
void main()
{
student arr[MAX];
for (int k=0; k<MAX; k++)
arr[k].input();
double hm=0, sum=0;
for (int x=0; x<MAX; x++)
{
arr[x].display1();
sum+=arr[x].marks();
if (hm>arr[x].marks())
hm=arr[x].marks();
}
double avg=sum/MAX;
cout<<"Highest="<<hm<<" & Average="<<avg<<endl;
}

Or,

void arrinput(student a[], int n)


{
for (int k=0; k<n; k++)
arr[k].input();
}
void arrdisplay(student a[], int n)
{
for (int k=0; k<n; k++)
arr[k].display1();
}
void arrhiav(student a[], int n)
{
double hm=0, sum=0;
for (int k=0; k<MAX; k++)
{
sum+=arr[k].marks();
if (hm>arr[k].marks())
hm=arr[k].marks();
}
double avg=sum/n;
cout<<"Highest="<<hm<<" & Average="<<avg<<endl;
}
void main()
{
student arr[MAX];
arrinput(arr, MAX);
arrdisplay(arr, MAX);
arrhiav(arr, MAX);
}
FAIPS, DPS Kuwait Page 16 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
void bubblesortroll(student arr[], int n)
{
for(int x=1; x<n; x++) Function to sort an array
for(int k=0; k<n-x; k++)
of student on roll
if (arr[k].roll()>arr[k+1].roll())
using bubble sort.
{
student t=arr[k];
arr[k]=arr[k+1];
arr[k+1]=t;
}
}
void selectionsortroll(student arr[], int n)
{
for(int x=0; x<n-1; x++)
Function to sort an array
{
of student on roll
student min=arr[x];
int pos=x; using selection sort.
for(int k=x+1; k<n; k++)
if (arr[k].roll()<min.roll())
{
min=arr[k];
pos=k;
}
arr[pos]=arr[x];
arr[x]=min;
}
}
void insertionsortroll(student arr[], int n)
{
for(int x=1; x<n; x++) Function to sort an array
{ of student on roll
student t=arr[x]; using insertion sort.
int k=x-1;
while(k>=0 && t.roll()<arr[k].roll())
{
arr[k+1]=arr[k];
k--;
}
arr[k+1]=t;
}
}
int linearsearchroll(student arr[], int n, int roll)
{
int x=0, found=0; Function to locate for a
while (x<n && found==0) roll in an array of
if (roll==arr[x].roll()) student using linear
found=1; search. Return value of the
else function is int. If search is
x++; successful function returns
return found; value 1 otherwise 0.
}
FAIPS, DPS Kuwait Page 17 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
void linearsearchroll(student arr[], int n, int roll)
{
int x=0, found=0; Function to locate for a
while (x<n && found==0) roll in an array of
if (roll ==arr[x].roll()) student using linear
found=1; search. Return value of the
else function is void. Status of
x++; search is displayed in the
if (found==1) function.
cout<<roll<<" Found in the array\n";
else
cout<<roll<<" Does not Exist in the array\n";
}
int binarysearchroll(student arr[], int n, int roll)
{
int lb=0, ub=n-1; Function to locate for a
int found=0, mid; roll in a sorted array of
while (lb<=ub && found==0) student using binary
{ search. Return value of the
mid=(ub+lb)/2; function is int. If search is
if (roll<arr[mid].roll()) successful function returns
ub=mid-1; value 1 otherwise 0.
else
if (roll>arr[mid].roll())
lb=mid+1;
else
found=1;
}
return found;
}
void binarysearchroll(student arr[], int n, int roll)
{
int lb=0, ub=n-1; Function to locate for a
int found=0, mid; roll in a sorted array of
while (lb<=ub && found==0) student using binary
{ search. Return value of the
mid=(ub+lb)/2; function is void. Status of
if (roll<arr[mid].roll()) search is displayed in the
ub=mid-1; function.
else
if (roll>arr[mid].roll())
lb=mid+1;
else
found=1;
}
if (found==1)
cout<<roll<<" Found in the array\n";
else
cout<<roll<<" Does not Exist in the array\n";
}

FAIPS, DPS Kuwait Page 18 of 50 © Bikram Ally


C++ Notes Class XII Classes and Objects
void bubblesortname(student arr[], int n)
{
for(int x=1; x<n; x++)
for(int k=0; k<n-x; k++)
if (strcmp(arr[k].name(), arr[k+1].name())>0)
{
student t=arr[k]; Function to sort an array
arr[k]=arr[k+1]; of student on name
arr[k+1]=t; using bubble sort.
}
}
void selectionsortname(student arr[], int n)
{
for(int x=0; x<n-1; x++) Function to sort an array
{ of student on name
student min=arr[x]; using selection sort.
int pos=x;
for(int k=x+1; k<n; k++)
if (strcmp(arr[k].name(), min.name())<0)
{
min=arr[k];
pos=k;
}
arr[pos]=arr[x];
arr[x]=min;
}
}
void insertionsortname(student arr[], int n)
{
for(int x=1; x<n; x++) Function to sort an array
{ of student on name
student t=arr[x]; using insertion sort.
int k=x-1;
while(k>=0 && strcmp(t.name(), arr[k].name())<0)
{
arr[k+1]=arr[k];
k--;
}
arr[k+1]=t;
}
}
int linearsearchname(student arr[], int n, char* name)
{
int x=0, found=0; Function to locate for a
while (x<n && found==0) name in an array of
if (strcmp(name, arr[x].name())==0) student using linear
found=1; search. Return value of the
else function is int. If search is
x++; successful function returns
return found; value 1 otherwise 0.
}
FAIPS, DPS Kuwait Page 19 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
void linearsearchname(student arr[], int n, char* name)
{
int x=0, found=0; Function to locate for a
while (x<n && found==0) name in an array of
if (strcmp(name, arr[x].name())==0) student using linear
found=1; search. Return value of the
else function is void. Status of
x++; search is displayed in the
if (found==1) function.
cout<<name<<" Found in the array\n";
else
cout<<name<<" Does not Exist in the array\n";
}
int binarysearchname(student arr[], int n, char* name)
{
int lb=0, ub=n-1; Function to locate for a
int found=0, mid; name in a sorted array of
while (lb<=ub && found==0) student using binary
{ search. Return value of the
mid=(ub+lb)/2; function is int. If search is
if (strcmp(name, arr[mid].name())<0) successful function returns
ub=mid-1; value 1 otherwise 0.
else
if (strcmp(name, arr[mid].name())>0)
lb=mid+1;
else
found=1;
}
return found;
}
void binarysearchname(student arr[], int n, char* name)
{
int lb=0, ub=n-1; Function to locate for a
int found=0, mid; name in a sorted array of
while (lb<=ub && found==0) student using binary
{ search. Return value of the
mid=(ub+lb)/2; function is void. Status of
if (strcmp(name, arr[mid].name())<0) search is displayed in the
ub=mid-1; function.
else
if (strcmp(name, arr[mid].name())>0)
lb=mid+1;
else
found=1;
}
if (found==1)
cout<<name<<" Found in the array\n";
else
cout<<name<<" Does not Exist in the array\n";
}

FAIPS, DPS Kuwait Page 20 of 50 © Bikram Ally


C++ Notes Class XII Classes and Objects
void mergeroll(student a[],student b[],student c[],int n1,int n2)
{
int i=0, j=0, k=0;
while (i<n1 && j<n2)
if (a[i].roll()<b[j].roll()) Function to merge two
c[k++]=a[i++]; arrays of student sorted
else on roll to obtain the
c[k++]=b[j++]; third array also sorted on
while (i<n1) roll. All three arrays are
c[k++]=a[i++]; sorted in ascending order
while (j<n2) on roll.
c[k++]=b[j++];
}
void mergename(student a[],student b[],student c[],int n1,int n2)
{
int i=0, j=0, k=0; Function to merge two
while (i<n1 && j<n2) arrays of student
if (strcmp(a[i].name(),b[j].name())<0) sorted on name to
c[k++]=a[i++]; obtain the third array
else also sorted on name.
c[k++]=b[j++]; All three arrays are
while (i<n1) sorted in ascending
c[k++]=a[i++]; order on name.
while (j<n2)
c[k++]=b[j++];
}
void arrinsert(student arr[], int& n, int pos, student item)
{
if (n==MAX) Function to insert an object in an
cout<<"Overflow\n"; array of student. MAX is a user
else defined constant representing size
{ of the array. Array name, number of
for (int x=n-1; x>=pos; x--) elements currently in the array,
arr[x+1]=arr[x]; position for insertion and the object
arr[pos]=item; that is to be inserted are passed as
n++; parameters to the function.
item.display2();
cout<<"Inserted in the array\n";
}
}
void arrdelete(student arr[], int& n, int pos)
{
if (n==0) Function to delete an object from an
cout<<"Underflow\n"; array of student. Parameter n
else represents number elements currently
{ in the array. Array name, number of
for (int x=pos+1; x<n; x++) elements currently in the array and
arr[x-1]=arr[x]; position for deletion are passed as
n--; parameters to the function.
}
}
FAIPS, DPS Kuwait Page 21 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
const MAX=20;
class array
{
int array[MAX];
public:
void arrinput();
void arrdisplay();
void arrsort();
void arrsearch();
};
void array::arrinput()
{
for (int k=0; k<MAX; k++)
array[k]=random(1000);
}
void array::arrdisplay()
{
for (int k=0; k<MAX; k++)
cout<<array[k]<<endl;
}
void array::arrsort()
{
for (int k=1; k<MAX; k++)
for (int x=0; x<MAX-k; x++)
if (array[x]>array[x+1];
{
int t=array[k];
array[k]=array[k+1];
array[k]=t;
}
}
void array::arrsearch()
{
int lb=0, ub=MAX-1, found=0, item, mid;
cout<<"Input integer value to search? "; cin>>item;
while (lb<=ub && found==0)
{
mid=(lb+ub)/2;
if (item<array[mid])
ub=mid-1;
else
if (item>array[mid])
lb=mid+1;
else
found=1;
}
if (found==1)
cout<<item<<" found in the array\n";
else
cout<<item<<" not found in the array\n";
}
FAIPS, DPS Kuwait Page 22 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
void main()
{
int ch;
array arrobj;
randomize();
do
{
cout<<"1. Input Array\n";
cout<<"2. Display Array\n";
cout<<"3. Sort Array\n";
cout<<"4. Search Array\n";
cout<<"0. Quit\n";
cout<<"Input Choice[0-4]? "; cin>>ch;
switch (ch)
{
case 1:arrobj.arrinput();break;
case 2:arrobj.arrdisplay();break;
case 3:arrobj.arrsort();break;
case 4:arrobj.arrsearch();break;
}
}
while (ch!=0);
}

Constructor: A variable of the fundamental type can be created and a value can be assigned to it
in one single C++ statement. An array variable or a structure variable can be created and value
can be assigned to it by using an initializer. Examples are given below:

char cvar='T'; Variables cvar, ivar and


int ivar=20;
dvar are also assigned
double dvar=30.25;
values at the point of
creation. Structure variable
char ar1[10]="Careless";
b1, array variables ar1,
int ar2[5]={23, 45, 67, 89, 17};
double ar3[5]={1.7, 3.8, 9.1, 4.5, 2.3}; ar2 and ar3 are initialized
using an initializer (values
struct batsman are assigned at the point of
{ creation).
char name[15];
int runs;
};
batsman b1={"Karthik", 46};

Till now, when working with classes and objects, first we create a class (declare a class with data
members and member functions), then we create an object and to store values in the data
member of the object, a public member function is invoked to either assign values or input
values to private data members of the object. Now we will learn how to initialize data members
of an object, when the object is getting created. To do that we will introduce a special public
member function of a class called constructor function. In fact a constructor function does
much more than that. We will learn more about constructor function later. An example is given
showing use of constructor function to assign values to data members of objects:
FAIPS, DPS Kuwait Page 23 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
class cric
{ Class cric has a special public member
char name[15]; function called cric() and it has 2
int runs; formal parameters. Values stored in the
public: parameters assigns values to the private
cric(char* n, int r) data members of the class cric.
{ Member function cric() is the
strcpy(name, n); constructor function of the class cric.
runs=r; Always class name and constructor
} function have same name.
void input()
{
cout<<"Name? "; gets(name);
cout<<"Runs? "; cin>>runs;
} cric c1=cric("Amar",103);
void display() statement invokes the constructor
{ function and assigns values to data
cout<<"Name="<<name<<endl; members of c1. This is way of
cout<<"Runs="<<runs<<endl; invoking constructor function is
} called explicit call to a constructor
}; function.
void main() cric c2("Kunal",88);
{ statement invokes the constructor
cric c1=cric("Amar", 103); function and assigns values to data
cric c2("Kunal", 88); members of c2. This is way of
c1.display(); invoking constructor function is
c2.display(); called implicit call to a constructor
} function.

But if we add the following statement in the main() function then the compiler will flag a
syntax error.

cric c3;

Compiler will add syntax error because it looks for a constructor function like cric(){ },
that is a constructor without any parameter and without any statement inside the function block
of the constructor function. Since no such constructor exists, compiler flags a syntax error. So
constructor function cric(){ } has to be added to the class cric. Edited class cric and the
complete program is given below:

class cric Now class cric has two constructors,


{ cric() and cric(char* n, int r). A
char name[15];
class can have many constructors. A class
int runs;
having many constructors is called
public:
constructor overloading. A constructor
cric() { }
cric(char* n, int r) function without any parameter is called
{ default constructor. A default constructor
strcpy(name, n); may or may not contain any statement
runs=r; (code). A constructor with parameter is
} called parameterized constructor.
FAIPS, DPS Kuwait Page 24 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
void input()
{
cout<<"Name? "; gets(name);
cout<<"Runs? "; cin>>runs;
}
void display()
{
cout<<"Name="<<name<<endl;
cout<<"Runs="<<runs<<endl;
}
};
void main()
{
cric c1, c2("Kunal", 88); Object c1 is created by default
c1.input();
constructor and object c2 is created
c1.display();
c2.display(); by parameterized constructor.
}

What is the role of constructor cric(){ }? It’s just creates an object. As mentioned earlier, a
constructor function does more that initialize values to data members of an object. In fact the
most important role of a constructor function is to create an object. Every object is created
by constructor. But classes declared earlier, did not have any constructor. So in that case how
were objects created without any constructor? When a class is created without any
constructor, compiler adds a default constructor (a constructor without any parameter), so
that instance of that class can be created. But once a class has a constructor, compiler does not
add default constructor and in that case default constructor has to be added by the programmer.
A constructor function can be defined inside the class and outside the class as well. An example
is given below:

class cric
{
char name[15];
int runs;
public:
cric(); All the member functions of class cric,
cric(char*, int); including constructor functions are declared
void input(); inside the class, but the all the member
void display(); functions are defined outside the class.
};
cric::cric() { }
cric::cric(char* n, int r)
{
strcpy(name, n);
runs=r;
}
void cric::input()
{
cout<<"Name? "; gets(name);
cout<<"Runs? "; cin>>runs;
}
FAIPS, DPS Kuwait Page 25 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
void cric::display()
{
cout<<"Name="<<name<<endl;
cout<<"Runs="<<runs<<endl;
}

Constructor function is a special public member function of a class that creates an object. A
Constructor functions have the following unique characteristics:
• Name of a constructor is same as that of a class name. If class name is cric then constructor
name is cric(), if class name is student then constructor name is student().
• A constructor function is defined / declared only in the public area of a class, that is, a
constructor is defined / declared with visibility label public only.
• A constructor function does not have any return value, not even void.
• A class can have many constructors.
• A constructor function is not inherited.

All types of constructors will be discussed in details. Our discussions regarding constructor will
be using class cric as reference. Only relevant constructor we be defined and main() function
will be defined whenever necessary.
• Default constructor is constructor without any parameter. Also it is a constructor added by
the compiler when there are no constructor functions defined / declared in a class. Example
of default constructor is given:

cric()
{ //No statement } First definition of default constructor
Or, cric() contains a empty block. Second
cric() definition of default constructor cric()
{ contains statements to initialize data
strcpy(name, ""); member name to "" (nul string) and
runs=0; data member runs to 0 (zero).
}

• Parameterised constructor is a constructor with parameter and it is always created


(defined) by a programmer. Example of parameterized constructor is given below:

cric(char* na, int ru) //1st Constructor


{
strcpy(name, na);
runs=ru;
}
cric(char* na) //2nd Constructor
{
strcpy(name, na);
runs=0;
}
cric(int ru) //3rd Constructor
{
strcpy(name, "NONAME");
runs=ru;
}

FAIPS, DPS Kuwait Page 26 of 50 © Bikram Ally


C++ Notes Class XII Classes and Objects
void main()
Class cric has three parameterized
{
cric c1("Kunal", 88); constructors. Object c1 is created with
cric c2("Kunal"), c3(88); 1st constructor, object c2 is created
//More C++ statement with 2nd constructor and object c3 is
} created with 3rd constructor.

• Constructor with default parameter is a parameterised constructor with default values


assigned to the formal parameters of the constructor function. Default values to the formal
parameters should always be assigned from right. Advantage of constructor with default
parameter is that, single constructor can replace default constructor and parameterized
constructor. Example of constructor with default parameter is given below:

cric(char* na="", int ru=0)


{
strcpy(name, na);
runs=ru; Object c1’s data members name and
} runs are assigned values "Kunal"
void main() and 88. Object c2’s data members
{ name and runs are assigned values
cric c1("Kunal", 88); "Kunal" and 0. Object c3’s data
cric c2("Kunal"), c3;
members name and runs are
//More C++ statement
} assigned values "" and 0.

• Copy constructor is a constructor function in which an object of the same class is passed by
reference to the constructor function. Copy constructor is used to duplicate an object when
the object is getting created. A copy constructor is added by the compiler when there is
no copy constructor defined in the class. Example of copy constructor is given below:

cric(char* na="", int ru=0)


Objects c1 and c2 are created by
{
//Parameterized Constructor parameterized constructor, objects c3
strcpy(name, na); and c4 are created by copy constructor
runs=ru; and object c5 is created by
} parameterized constructor. Object c3
cric(cric& c) is a duplicate of object c2 and object c4
{ is a duplicate of object c1. But object
//Copy Constructor c5 obtains the values of object c1
strcpy(name, c.name); through assignment operator because
runs=c.runs; object c5 has been created already.
} Constructor is invoked only once to
void main() create an object. There are two ways to
{ invoke copy constructor:
cric c1("Kunal", 88); 1. cric c3=c2;
cric c2("Afzal", 42);
2. cric c4(c1);
cric c3=c2, c4(c1);
cric c5;
c5=c1;
//More C++ statement
}
FAIPS, DPS Kuwait Page 27 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
Constructor Overloading: A class having more than one constructor functions, that is, objects
can be created in more than one ways. Example of constructor overloading is given below:

cric(char* na="", int ru=0)


{
strcpy(name, na);
runs=ru;
}
cric(cric& c)
{
strcpy(name, c.name);
runs=c.runs;
}

Or,

cric()
{
strcpy(name, "");
runs=0;
}
cric(char* na, int ru)
{
strcpy(name, na);
runs=ru;
}
cric(char* na)
{
strcpy(name, na);
runs=0;
}
cric(int ru)
{
strcpy(name, "NONAME");
runs=ru;
}
cric(cric& c)
{
strcpy(name, c.name);
runs=c.runs;
}

Constructor function is a special public member function of a class, used to create an object.
Once an object is created, it must be destroyed, so we have another special public member
function called destructor function of class to reclaim resources allocated to an object (destroys
an object). A destructor function is invoked automatically when an object goes out of scope.

Every object is created by a constructor and destroyed by a destructor. If a destructor is not


defined / declared in a class, then the compiler adds one. In most case destructor added by the
compiler is sufficient to destroy an object but for some special cases, destructor function has to
be added by the programmer.
FAIPS, DPS Kuwait Page 28 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
Destructor is a special public member function of a class that destroys an object, when an
object goes out of scope. A complete program is given below showing use destructor:

class cric
{ Constructor of class cric is
char name[15]; cric(). Destructor of class
int runs; cric is ~cric(). Destructor of
public: class starts with ~ (tilde
cric(char* n="", int r=0) character) followed by class name
{ (cric). Destructor ~cric()
strcpy(name, n); displays a message on the screen.
runs=r; Object obj is created by
} constructor cric(). Statement
~cric()
obj.display(), displays value
{
stored in the data members of
cout<<"Object Destroyed\n";
} object obj. When program
void input() terminates, object obj goes out
{ of scope, that is, destructor
cout<<"Name? "; gets(name); ~cric() is invoked and Object
cout<<"Runs? "; cin>>runs; Destroyed is displayed on the
} screen.
void display()
{ Execution of the program
cout<<"Name="<<name<<endl; produces following output on the
cout<<"Runs="<<runs<<endl; screen:
} Name=Rajat
}; Runs=103
void main() Object Destroyed
{
cric obj("Rajat", 103);
obj.display();
}

Destructor functions have the following unique characteristics:


• Destructor function name begin with ~ (tilde character) and followed by class name
• A destructor function is defined / declared only in the public area of a class, that is, a
constructor is defined / declared with visibility label public only.
• A destructor function does not have any return value, not even void.
• A class can have only one destructor.
• A destructor function does not have any parameter.
• A destructor function is invoked automatically.
• A destructor function is not inherited

FAIPS, DPS Kuwait Page 29 of 50 © Bikram Ally


C++ Notes Class XII Classes and Objects
Visibility Label protected: Till now we have only discussed visibility labels public and
private. Now is the right time to introduce third visibility label, protected. A private member
can be used inside the class where as a public member can used inside and as well as outside the
class. A protected member can be used inside the class – similar to a private member but it can
be inherited – similar to a public member. Private member cannot be inherited. Inheritance
means creating a new class from an old class such that, new class can access public and
protected members of the old class (public and protected members of the old class become
members of new class).

Inheritance: Inheritance is a process of creating a new class (derived classes or sub classes)
from old class (base class or super class). The derived class acquires some properties of base
class and derived class also adds new features of its own. Acquiring certain properties from base
class means that public and protected members of a base class also become members of a
derived class. It also implies public and protected members of a base class can be accessed
from a derived class. Private members of base class cannot be accessed by derived class
(private members cannot be inherited). The process of Inheritance does not affect the base class.
A derived class is created by specifying its relationship with the base class in addition to its own
details.

Rule: class DerivedClassName: AccSpec BaseClassName


{
//Members of Derived Class
};

The colon indicates that the DerivedClassName is created (derived / defined) from
BaseClassName. Access specifier (AccSpec)can either be public or protected or
private. Access specifier is optional. The default access specifier is private. Access specifier
specifies whether features of base class are publicly or protectedly or privately derived. An
example is given below:

class oldclass Base class oldclass


{ • Private member: a
int a; • Inheritable members
protected:  Protected member: b, ocp()
char b;  Public member: c, ocf()
void ocp();
public:
double c;
void ocf(); Derived class newclass
}; • Private member: x
class newclass: public oldclass
• Protected members
{
 Own: y, ncp()
double x;
protected:  Inherited: b, ocp()
int y; • Public members
void ncp();  Own: z, ncf()
public:  Inherited: c, ocf()
char z; Arrow head pointing down implies that
void ncf(); the newclass is derived from
}; oldclass.

FAIPS, DPS Kuwait Page 30 of 50 © Bikram Ally


C++ Notes Class XII Classes and Objects
Base class is oldclass, from base class oldclass a new class is created named newclass
(derived class). Public members of oldclass (c, and ocf()) and protected members of
oldclass (b, ocp()) become members of newclass. But private members of oldclass,
a remain private to oldclass, that is, they are not inherited. Since AccessSpecifier is
public, public and protected members of base class retain their old visibility label in the derived
class (public members of base class remains public and protected members of base class remain
protected in the derived class). A complete programming example is given below:

class person
{
char name[20];
int mobile;
public:
void inputperson()
{
cout<<"Name ? "; gets(name);
cout<<"Mobile ? "; cin>>mobile;
}
void displayperson()
{
cout<<"Name : "<<name<<endl;
cout<<"Mobile : "<<mobile<<endl;
}
};
class employee: public person
{
int eno;
char designation[40];
double basic;
public:
void inputemp()
{
cout<<"Emp Number ? "; cin>>eno;
cout<<"Designation? "; gets(designation);
cout<<"Basic Pay ? "; cin>>basic;
}
void displayemp()
{
cout<<"Emp Number : "<<eno<<endl;
cout<<"Designation: "<<designation<<endl;
cout<<"Basic Pay : "<<basic<<endl;
}
};
void main()
{
employee obj;
obj.inputperson();
obj.inputemp();
obj.displayperson();
obj.displayemp();
}
FAIPS, DPS Kuwait Page 31 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
Running of the program produces following output:

Name ? Shankar N Gupta


Mobile ? 99637248
Emp Number ? 21
Designation? Network Administrator
Basic Pay ? 2100
Name : Shankar N Gupta
Mobile : 99637248
Emp Number : 21
Designation: Network Administrator
Basic Pay : 2100

• When memory is allocated to an instance of derived class (in our example employee is
the derived class and obj is an instance of employee), memory allocated for data
members of base class (including memory allocated for the private members of base
class plus data members of derived class).
• In our example memory allocated to instance of employee is 80 bytes (20 bytes for
name, 4 bytes each for phone and mobile plus 4 bytes for eno, 40 bytes for
designation and 8 bytes for basic).
• Even though the memory is allocated for the private members of the base class, member
functions of derived class cannot access private members of the base class.
• Private members of the base class are access by member functions of base class.
• In our example, inputperson() and displayperson() are the public member
functions of base class, person. Through inheritance, inputperson() and
displayperson() become member of derived class employee.
• Member functions inputperson() and displayperson() is invoked from an
instance of employee to access the private members of base class person.

What happens when access specifier is changed from public to private (protected)? As
mentioned earlier, if access specifier is public, then inherited members in the derived class
retains the visibility label of the base class. But if access specifier is private (protected) then all
the inherited members become private (protected) member in the derived class. A private
(protected) member cannot be used outside the class. Consider the main() function given
below:

void main()
{
employee empobj;
empobj.inputperson();
empobj.inputemp();
empobj.displayperson();
empobj.displayemp();
}

Assuming that access specifier is either private or protected, statements


obj.inputperson(); and obj.displayperson(); would flag syntax errors. Therefore
member functions of class person, inputperson() and displayperson() are to be
invoked from member functions class employee. Edited program is given in the next page:

FAIPS, DPS Kuwait Page 32 of 50 © Bikram Ally


C++ Notes Class XII Classes and Objects
class person
{
char name[20];
int mobile;
public:
void inputperson()
{
cout<<"Name ? "; gets(name);
cout<<"Mobile ? "; cin>>mobile;
}
void displayperson()
{
cout<<"Name : "<<name<<endl;
cout<<"Mobile : "<<mobile<<endl;
}
};
class employee: private person
{
int eno;
char designation[40];
double basic;
public:
void inputemp()
{
inputperson(); //Base class member function
cout<<"Emp Number ? "; cin>>eno;
cout<<"Designation? "; gets(designation);
cout<<"Basic Pay ? "; cin>>basic;
}
void displayemp()
{
displayperson(); //Base class member function
cout<<"Emp Number : "<<eno<<endl;
cout<<"Designation: "<< designation <<endl;
cout<<"Basic Pay : "<<basic<<endl;
}
};
void main()
{
employee obj;
obj.inputemp();
obj.displayemp();
}

Running of the program produces following output:

Name ? Shankar N Gupta


Mobile ? 99637248
Emp Number ? 21
Designation? Network Administrator
Basic Pay ? 2100
FAIPS, DPS Kuwait Page 33 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
Name : Shankar N Gupta
Mobile : 99637248
Emp Number : 21
Designation: Network Administrator
Basic Pay : 2100

• Access specifier is private (or protected but the code would have remained the same)
• Base class member function inputperson() is invoked from derived class member
function inputemp()
• Base class member function displayperson() is invoked from derived class member
function displayemp()

Single Level Inheritance: A derived class has one base class (or a base class has only one
derived class).

Rule: class BaseClassName


{
//Members of Base Class
};
class DerivedClassName: AccSpec BaseClassName
{
//Members of Derived Class
};

Only public and protected members of base class are inherited by derived class
(public and protected members of base class become members of derived class).
Access specifier (AccSpec) is either public or protected or private.

Example: Base Class


class person
{
char name[20];
int mobile; Derived Class
public:
void inputperson()
{
cout<<"Name ? "; gets(name);
cout<<"Mobile ? "; cin>>mobile;
}
void displayperson()
{
cout<<"Name : "<<name<<endl;
cout<<"Mobile : "<<mobile<<endl;
}
};
class employee: public person
{
int eno;
char designation[40];
double basic, hra, gross;

FAIPS, DPS Kuwait Page 34 of 50 © Bikram Ally


C++ Notes Class XII Classes and Objects
public:
void inputemp()
{
cout<<"Emp Number ? "; cin>>eno;
cout<<"Designation? "; gets(designation);
cout<<"Basic Pay ? "; cin>>basic;
hra=0.35*basic; gross=basic+hra;
}
void displayemp()
{
cout<<"Emp Number : "<<eno<<endl;
cout<<"Designation: "<<designation<<endl;
cout<<"Basic Pay : "<<basic<<endl;
cout<<"House Rent : "<<hra<<endl;
cout<<"Gross Pay : "<<gross<<endl;
}
};
void main()
{
employee obj;
obj.inputperson();
obj.inputemp();
obj.displayperson();
obj.displayemp();
}

Multi-level Inheritance: A new class is derived from a derived class, that is, between top most
base class and bottom most derived there is at least one intermediate class.

Rule: class BaseClass


{
//Members of Base Class
};
class InterDerClass1: AccSpec1 BaseClass
{
//Members of 1st Intermediate Class
};
class InterDerClass2: AccSpec2 InterClass1
{
//Members of 2nd Intermediate Class
};
class DeriveClass: AccSpec3 InterClass2
{
//Members of Derived Class
};

Classes InterDerClass1 and InterDerClass2 represent intermediate derived


classes between top most base class (BaseClass) and bottom most derived class
(DeriveClass). If access specifier (AccSpec1, AccSpec2, AccSpec3) is either
public or protected then members inherited by an intermediate derived class can be further
inherited by classes derived from intermediate derived class.
FAIPS, DPS Kuwait Page 35 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
Example: Top Most
class person
Base Class
{
char name[20];
int mobile; Intermediate
public: Derived Class 1
void inputperson()
{
cout<<"Name ? "; gets(name); Intermediate
cout<<"Mobile ? "; cin>>mobile; Derived Class 2
}
void displayperson()
{ Bottom Most
cout<<"Name : "<<name<<endl; Derived Class
cout<<"Mobile : "<<mobile<<endl;
}
};
class employee: public person
{
int eno;
char designation[40];
public:
void inputemp()
{
cout<<"Emp Number ? "; cin>>eno;
cout<<"Designation? "; gets(designation);
}
void displayemp()
{
cout<<"Emp Number : "<<eno<<endl;
cout<<"Designation: "<<designation<<endl;
}
};
class salary: public employee
{
double basic, hra, da, gross;
public:
void inputsal()
{
cout<<"Basic Sal ? "; cin>>basic;
hra=0.3*basic; da=0.4*basic;
gross=basic+hra+da;
}
void displaysal()
{
cout<<"Basic Sal : "<<basic<<endl;
cout<<"House Rent : "<<hra<<endl;
cout<<"DA : "<<da<<endl;
cout<<"Gross Sal : "<<gross<<endl;
}
};
FAIPS, DPS Kuwait Page 36 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
void main()
{
salary obj;
obj.inputperson();
obj.inputemp();
obj.inputsal();
obj.displayperson();
obj.displayemp();
obj.displaysal();
}

Running of the program produces following output:

Name ? Sushant Gupta


Mobile ? 93150342
Emp Number ? 45
Designation? Business Manager
Basic Sal ? 65000
Name : Sushant Gupta
Mobile : 93150342
Emp Number : 45
Designation: Business Manager
Basic Sal : 65000
House Rent : 19500
DA : 26000
Gross Sal : 110500

Intermediate derived class employee is derived publically from class person, therefore
members inherited by class employee are ready to be inherited further. Derived class
salary further inherits members inherited by class employee (from class person).
Member functions inputperson() and displayperson() are inherited by class
employee from base class person. Class salary further inherits these two member
functions of class employee through class person. That is the reason it is possible to
invoke functions inputperson() and displayperson() from an instance of salary.
If intermediate derived class was derived protectedly (private) from class person, class
salary would still have inherited functions inputperson() and displayperson() but
as protected (private) members. Hence they had to be invoked either from member
functions of class employee. Edited program is given below:

class person
{
char name[20];
int mobile;
public:
void inputperson()
{
cout<<"Name ? "; gets(name);
cout<<"Mobile ? "; cin>>mobile;
}

FAIPS, DPS Kuwait Page 37 of 50 © Bikram Ally


C++ Notes Class XII Classes and Objects
void displayperson()
{
cout<<"Name : "<<name<<endl;
cout<<"Mobile : "<<mobile<<endl;
}
};
class employee: protected person
{
int eno;
char designation[40];
public:
void inputemp()
{
inputperson();
cout<<"Emp Number ? "; cin>>eno;
cout<<"Designation? "; gets(designation);
}
void displayemp()
{
displayperson();
cout<<"Emp Number : "<<eno<<endl;
cout<<"Designation: "<<designation<<endl;
}
};
class salary: public employee
{
double basic, hra, da, gross;
public:
void inputsal()
{
cout<<"Basic Sal ? "; cin>>basic;
hra=0.3*basic;
da=0.4*basic;
gross=basic+hra+da;
}
void displaysal()
{
cout<<"Basic Sal : "<<basic<<endl;
cout<<"House Rent : "<<hra<<endl;
cout<<"DA : "<<da<<endl;
cout<<"Gross Sal : "<<gross<<endl;
}
};
void main()
{
salary obj;
obj.inputemp();
obj.inputsal();
obj.displayemp();
obj.displaysal();
}
FAIPS, DPS Kuwait Page 38 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
Member function inputperson() and displayperson() are invoked from member
function of class employee – inputemp() and displayemp() respectively because
inputperson() and displayperson() are protected members of class employee. If
access specifier was private at every level, then all the inherited member functions had to be
invoked from member functions of derived class. An example is given:

class person
{
char name[20];
int mobile;
public:
void inputperson()
{
cout<<"Name ? "; gets(name);
cout<<"Mobile ? "; cin>>mobile;
}
void displayperson()
{
cout<<"Name : "<<name<<endl;
cout<<"Mobile : "<<mobile<<endl;
}
};
class employee: private person
{
int eno;
char designation[40];
public:
void inputemp()
{
inputperson();
cout<<"Emp Number ? "; cin>>eno;
cout<<"Designation? "; gets(designation);
}
void displayemp()
{
displayperson();
cout<<"Emp Number : "<<eno<<endl;
cout<<"Designation: "<<designation<<endl;
}
};
class salary: private employee
{
double basic, hra, da, gross;
public:
void inputsal()
{
inputemp();
cout<<"Basic Sal ? "; cin>>basic;
hra=0.3*basic; da=0.4*basic;
gross=basic+hra+da;
}
FAIPS, DPS Kuwait Page 39 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
void displaysal()
{
displayemp();
cout<<"Basic Sal : "<<basic<<endl;
cout<<"House Rent : "<<hra<<endl;
cout<<"DA : "<<da<<endl;
cout<<"Gross Sal : "<<gross<<endl;
}
};
void main()
{
salary obj;
obj.inputsal();
obj.displaysal();
}

Since classes are derived privately, inherited members become private members in the
derived class, meaning, those inherited members has to be used inside (if data member) or
invoked from (if member function) member functions of derived class. Also those inherited
members cannot be inherited further. But those members can be accessed indirectly through
the member functions of immediate base class. In our example, inputperson() is invoked
from inputemp() and inputemp() is invoked from inputsal() and
displayperson() is invoked from displayemp() and displayemp() is invoked from
displaysal(). From main() function, only two functions are invoked, inputsal() and
displaysal() – the public member functions of object obj. Input of data is done by
invoking member function inputsal(), inputsal() invokes inputemp() and
inputemp() invokes inputperson(). Output is displayed on the screen by invoking
member function displaysal(), displaysal() invokes displayemp() and
displayemp() invokes displayperson().

Multiple Inheritance: A new class is derived from more than two or more (at least two) base
classes (or a derived class has two or more base classes – at least two base classes).

Rule: class BaseClass1


{
//Members of 1st Base Class
};
class BaseClass2
{
//Members of 2nd Base Class
};
class DeriveClass: AccSpec1 BaseClass1, AccSpec2 BaseClass2
{
//Members of Derived Class
};

Classes BaseClass1 and BaseClass2 represent two base classes. Class DeriveClass
is derived from BaseClass1 and BaseClass2. If access specifier (AccSpec1,
AccSpec2) is either public or protected then members inherited by DeriveClass class
can be further inherited by classes derived from DeriveClass.
FAIPS, DPS Kuwait Page 40 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects

Base Class1 Base Class2

Example:
class student
Derived Class
{
int sroll;
char sname[20];
public:
void inputstud()
{
cout<<"Student Roll ? "; cin>>sroll;
cout<<"Student Name ? "; gets(sname);
}
void displaystud()
{
cout<<"Student Roll : "<<sroll<<endl;
cout<<"Student Name : "<<sname<<endl;
}
};
class teacher
{
int tcode;
char tname[20];
public:
void inputteach()
{
cout<<"Teacher Code ? "; cin>>tcode;
cout<<"Teacher Name ? "; gets(tname);
}
void displayteach()
{
cout<<"Teacher Roll : "<<tcode<<endl;
cout<<"Teacher Name : "<<tname<<endl;
}
};
class school: public student, public teacher
{
char schname[40];
char priname[20];
char board[20];
public:
void inputscho()
{
cout<<"School Name ? "; gets(schname);
cout<<"Principal Name? "; gets(priname);
cout<<"Board ? "; cin>>board;
}
FAIPS, DPS Kuwait Page 41 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
void displayscho()
{
cout<<"School Name : "<<schname<<endl;
cout<<"Principal Name: "<<priname<<endl;
cout<<"Board : "<<board<<endl;
}
};
void main()
{
school obj;
obj.inputstud();
obj.inputteach();
obj.inputscho();
obj.displaystud();
obj.displayteach();
obj.displayscho();
}

Running of the program produces following output:

Student Roll ? 19
Student Name ? Sudhir Kr Jain
Teacher Code ? 1023
Teacher Name ? Vimal Garg
School Name ? Elite International School
Principal Name? Suman Rani Bhalla
Board ? CBSE
Student Roll : 19
Student Name : Sudhir Kr Jain
Teacher Roll : 1023
Teacher Name : Vimal Garg
School Name : Elite International School
Principal Name: Suman Rani Bhalla
Board : CBSE

Hierarchical Inheritance: Two or more classes (at least two derived classes) are derived from
single base classes (or two or more derived classes have single base class).

Rule: class BaseClass


{
//Members of Base Class
};
class DeriveClass1: AccSpec1 BaseClass
{
//Members of 1st Derive Class
};
class DeriveClass2: AccSpec2 BaseClass
{
//Members of 2nd Derive Class
};

FAIPS, DPS Kuwait Page 42 of 50 © Bikram Ally


C++ Notes Class XII Classes and Objects
Classes DeriveClass1 and DeriveClass2 are two derived classes derived from single
base class BaseClass. If access specifier (AccSpec1, AccSpec2) is either public or
protected then members inherited by classes DeriveClass1 and DeriveClass2 can be
further inherited by classes derived from DeriveClass1 and DeriveClass2.

Base Class

Example:
class person
{
char name[30];
int phone;
Derived Class1 Derived Class2
char address[70];
public:
void inputpers()
{
cout<<"Name ? "; gets(name);
cout<<"Phone ? "; cin>>phone;
cout<<"Address ? "; gets(address);
}
void showpers()
{
cout<<"Name : "<<name<<endl;
cout<<"Phone : "<<phone<<endl;
cout<<"Address : "<<address<<endl;
}
};
class staff: public person
{
int eno;
char designation[30];
double salary;
public:
void inputstaff()
{
cout<<"Emp Number ? "; cin>>eno;
cout<<"Designation? "; gets(designation);
cout<<"Monthly Pay? "; cin>>salary;
}
void showstaff()
{
cout<<"Emp Number : "<<eno<<endl;
cout<<"Designation: "<<designation<<endl;
cout<<"Monthly Pay: "<<salary<<endl;
}
};
class tempstaff: public person
{
char particular[30];
double hrwage;
public:
FAIPS, DPS Kuwait Page 43 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
void inputtemp()
{
cout<<"Particular ? "; gets(particular);
cout<<"Hourly Wage? "; cin>>hrwage;
}
void showtemp()
{
cout<<"Particular : "<<particular<<endl;
cout<<"Hourly Wage: "<<hrwage<<endl;
}
};
void main()
{
staff obj1;
obj1.inputpers();
obj1.inputstaff();
obj1.showpers();
obj1.showstaff();
cout<<endl;
tempstaff obj2;
obj2.inputpers();
obj2.inputtemp();
obj2.showpers();
obj2.showtemp();
}

Running of the program produces following output:

Name ? Dinesh John Mathew


Phone ? 23921834
address ? Building-6, Flat-12, Street-28, Mangaf-3
Emp Number ? 1017
Designation? Marketing Manager
Monthly Pay? 2500
Name : Dinesh John Mathew
Phone : 23921834
Address : Building-6, Flat-12, Street-28, Mangaf-3
Emp Number : 1017
Designation: Marketing Manager
Monthly Pay: 2500

Name ? Lakshman Singh


Phone ? 23725692
address ? House-45, Street-39, North Ahmadi
Particular ? Part time worker
Hourly Wage? 2.5
Name : Lakshman Singh
Phone : 23725692
Address : House-45, Street-39, North Ahmadi
Particular : Part time worker
Hourly Wage: 2.5
FAIPS, DPS Kuwait Page 44 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
Abstract class and Concrete class: A class without an instance is called Abstract class where
as a class with an instance is called Concrete class. An Example is given below:

class bclass
{
int a, b;
public:
void inputbc()
{
cout<<"Input a? "; cin>>a;
cout<<"Input b? "; cin>>b;
}
void showbc()
{
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;
}
};
class dclass: public bclass
{
double x, y;
public:
void inputdc()
{
cout<<"Input x? "; cin>>x;
cout<<"Input y? "; cin>>y;
}
void showdc()
{
cout<<"x="<<x<<endl;
cout<<"y="<<y<<endl;
}
}; Class bclass is base class and class
void main() dclass is derived from bclass. In
{ the main() function there is an instance
dclass obj;
of dclass, obj. Hence bclass is
obj.inputbc();
Abstract class (without any instance)
obj.inputdc();
obj.showbc(); and dclass is a Concrete class (has
obj.showdc(); an instance).
}

Inheritance, Constructor and Destructor: Constructor and destructor functions are never
inherited. But constructor and destructor play a very important role in creating object and
deleting object, that is, base class constructor will create base class object (resources will be
allocated for base class members) and derived class constructor will create derived class objects
(resources will be allocated for derived class members). In case of multi-level inheritance, the
constructors will be executed in the order of inheritance. While in case of multiple inheritance,
the constructors will be executed in the order in which they appear in the declaration of the
derived class. Order of execution of destructor will be the reverse order of execution of
constructor.
FAIPS, DPS Kuwait Page 45 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
//Constructor and Destructor in multi-level inheritance
class AAA
{
char strA[5];
public:
AAA()
{
cout<<"Constructor of AAA\n"; strcpy(strA, "AAA");
}
void showAAA() { cout<<"strA = "<<strA<<endl; }
~AAA() { cout<<"Destructor of AAA\n"; }
};
class BBB: public AAA
{
char strB[5];
public:
BBB()
{
cout<<"Constructor of BBB\n"; strcpy(strB, "BBB");
}
void showBBB() { cout<<"strB = "<<strB<<endl; }
~BBB() { cout<<"Destructor of BBB\n"; }
};
class CCC: public BBB
{
char strC[5];
public:
CCC()
{
cout<<"Constructor of CCC\n"; strcpy(strC, "CCC");
}
void showCCC() { cout<<"strC = "<<strC<<endl; }
~CCC() { cout<<"Destructor of CCC\n"; }
};
void main()
{
CCC obj;
obj.showAAA(); obj.showBBB(); obj.showCCC();
}

Running of the program produces following output:

Constructor of AAA
Constructor of BBB Class BBB is derived from class AAA and class CCC is
Constructor of CCC derived from class BBB. Therefore constructors of
strA = AAA three classes are executed in that order, that is, first
strB = BBB constructor of AAA executed, then constructor of BBB
strC = CCC is executed and finally constructor of CCC is executed.
Destructor of CCC Destructors are invoked in the reverse order. First
Destructor of BBB destructor of CCC is invoked, then destructor of BBB
Destructor of AAA is invoked and finally destructor of AAA is invoked.
FAIPS, DPS Kuwait Page 46 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
//Constructor and Destructor in multiple inheritance #1
class AAA
{
char strA[5];
public:
AAA()
{
cout<<"Constructor of AAA\n"; strcpy(strA, "AAA");
}
void showAAA() { cout<<"strA = "<<strA<<endl; }
~AAA() { cout<<"Destructor of AAA\n"; }
};
class BBB
{
char strB[5];
public:
BBB()
{
cout<<"Constructor of BBB\n"; strcpy(strB, "BBB");
}
void showBBB() { cout<<"strB = "<<strB<<endl; }
~BBB() { cout<<"Destructor of BBB\n"; }
};
class CCC: public AAA, public BBB
{
char strC[5];
public:
CCC()
{
cout<<"Constructor of CCC\n"; strcpy(strC, "CCC");
}
void showCCC() { cout<<"strC = "<<strC<<endl; }
~CCC() { cout<<"Destructor of CCC\n"; }
};
void main()
{
CCC obj;
obj.showAAA(); obj.showBBB(); obj.showCCC();
}

Running of the program produces following output:

Constructor of AAA Class CCC is declared as:


Constructor of BBB class CCC: public AAA, public BBB
Constructor of CCC { //Members of CCC };
strA = AAA Base class constructors are executed in the order in which they
strB = BBB appear in the declaration of the derived class. Constructor of
strC = CCC AAA is executed first, then constructor of BBB is executed
Destructor of CCC and constructor of CCC is executed last. Destructors are
Destructor of BBB invoked in the reverse order – CCC's destructor first, BBB's
Destructor of AAA destructor next and last AAA's destructor.
FAIPS, DPS Kuwait Page 47 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
//Constructor and Destructor in multiple inheritance #2
class AAA
{
char strA[5];
public:
AAA()
{
cout<<"Constructor of AAA\n"; strcpy(strA, "AAA");
}
void showAAA() { cout<<"strA = "<<strA<<endl; }
~AAA() { cout<<"Destructor of AAA\n"; }
};
class BBB
{
char strB[5];
public:
BBB()
{
cout<<"Constructor of BBB\n"; strcpy(strB, "BBB");
}
void showBBB() { cout<<"strB = "<<strB<<endl; }
~BBB() { cout<<"Destructor of BBB\n"; }
};
class CCC: public BBB, public AAA
{
char strC[5];
public:
CCC()
{
cout<<"Constructor of CCC\n"; strcpy(strC, "CCC");
}
void showCCC() { cout<<"strC = "<<strC<<endl; }
~CCC() { cout<<"Destructor of CCC\n"; }
};
void main()
{
CCC obj;
obj.showAAA(); obj.showBBB(); obj.showCCC();
}

Running of the program produces following output:

Constructor of BBB Class CCC is declared as:


Constructor of AAA class CCC: public BBB, public AAA
Constructor of CCC { //Members of CCC };
strA = AAA Base class constructors are executed in the order in which they
strB = BBB appear in the declaration of the derived class. Constructor of
strC = CCC BBB is executed first, then constructor of AAA is executed
Destructor of CCC and constructor of CCC is executed last. Destructors are
Destructor of AAA invoked in the reverse order – CCC's destructor first, AAA's
Destructor of BBB destructor next and last BBB's destructor.
FAIPS, DPS Kuwait Page 48 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
Polymorphism: The process of using an operator or a function in different ways for different set
of inputs given is known as polymorphism (or functions and operators have same name but
perform different actions depending on formal parameters).

In C++ polymorphism is implemented through Function Overloading, Operator Overloading


and Virtual Function. But Operator Overloading and Virtual Function are not included in the
syllabus. When two or more functions with the same name work with different set of parameters
to perform different operations is known as Function Overloading, that is, functions are
differentiated on the basis of formal parameters.

Example 1:
void print() { cout<<"Summer Break is Over!"<<endl; }
void print(int n) { cout<<"Integer = "<<n<<endl; }
void print(double m) { cout<<"Double = "<<m<<endl; }
void print(char s[]){ cout<<"String = "<<s<<endl; }
void main()
{ Function print() is an Overloaded
print(90); Function, differentiate on the basis of data
print("Back to School!"); type of formal parameter. There are 4
print(12.75); definitions of function print() – without
print(); any parameter, int parameter, double
} parameter and string parameter.

Running of the program produces following output:

Integer = 90
String = Back to School
Double = 12.75
Happy Holidays!

Example 2:
void area(int si)
{
int sa=si*si;
cout<<"Area of Square = "<<sa<<endl;
}
void area(double ra)
{
double ca=3.14159*ra*ra;
cout<<"Area of Circle = "<<ca<<endl;
}
void area(int le, int br)
{
int ra=le*br;
cout<<"Area of Rectangle = "<<ra<<endl;
}
void area(double hi, double ba)
{
double ta=0.5*hi*ba;
cout<<"Area of Triangle = "<<ta<<endl;
}
FAIPS, DPS Kuwait Page 49 of 50 © Bikram Ally
C++ Notes Class XII Classes and Objects
void main()
Function area() is an Overloaded Function,
{
area(7.5); differentiate on the basis of data type of formal
area(10, 5); parameter and number of formal parameters.
area(12.5, 3.5); There are 4 definitions of function area() – one
area(15); int parameter, two int parameters, one double
} parameter and two double parameters.

Running of the program produces following output:

Area of Circle = 176.714


Area of Rectangle = 50
Area of Triangle = 21.875
Area of Square = 225

Object Oriented Program Procedural Oriented Program


• Equal emphasis is on data and functions • Emphasis is on doing things (Functions)
• Concept of Data Hiding prevents accidental • Excessive use of global variables may
change in the data result in accidental change of data.
• Supports Polymorphism, Inheritance and • Does not support Polymorphism,
Encapsulation Inheritance and Encapsulation

Visibility Label Accessibility Inheritable


Public Can be used inside the class as well as outside the class Yes
Protected Can be used inside the class only Yes
Private Can be used inside the class only No

Base Class Visibility Access Specifier Derived Class Visibility Further Inheritable
Public Public
Public Yes
Protected Protected
Public Protected
Protected Yes
Protected Protected
Public Private
Private No
Protected Private

FAIPS, DPS Kuwait Page 50 of 50 © Bikram Ally

You might also like