Download as pdf or txt
Download as pdf or txt
You are on page 1of 149

OBJECT ORIENTED PROGRAMMING(CS-1202)

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 1
What is Constructor?
• A constructor is a special member function of a
class that is executed whenever we create new
objects of that class.
• Constructor is automatically called when the object is
created. Constructors are not usually called explicitly
by us.
• Constructor is used to initialize the objects of a
class.
• Constructor Properties
− Constructor is a special function having same name as the
class name
− Constructor does not have return type
− Constructors are commonly public members
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 2
What would happen if we called the member function
area( ) before having called set values(int a,int b)???

#include<iostream> void main()


#include<conio.h> {
usingnamespace std;
rectangle rect ,rectb;
class rectangle
{ rect.set_values(3,4);
private:
int width, height; cout<<"area="<<rect.area()<
public: <endl;
void set_values(int a, int b);
int area(); rectb.set_values(5,7);
};
void rectangle::set_values(int a, int b) cout<<"area="<<rectb.area();
{
getch();
width=a;
height=b; }
}
int rectangle:: area()
{

return width*height;
}
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 3
• An undetermined result since the member
height and width have never been assigned
a value.

• In order to avoid that , a class can include a


special function, called the constructor which
is automatically called whenever a new object
of class is created, allowing the class to
initialize member variables or allocate
storage.

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 4
Syntax:

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 5
Example

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 6
Example:
• #include <iostream>
• #include<conio.h>
• using namespace std;

• class test
• {
• public:
• test( )
• {
• cout<<"welcome"<<endl;
• }
• };
• int main(int argc, char** argv) {
• test a,b,c;
• getch();
• return 0;
• }
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 7
Example:
• #include <iostream>
• #include<conio.h> int main( ) {
• using namespace std; myclass ob; // automatic call to
constructor
• class myclass { ob.show( );
• int a;
return 0;
}
• public:
• myclass( ); //constructor
• void show( );
• };
• myclass::myclass( )
• {
• a=10;
• }
• void myclass::show( )
• {
• cout << a;
• } C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 8
Example
#include<iostream> void main()
#include<conio.h> {
usingnamespace std;
rectangle rect ,rectb;
class rectangle
{ cout<<"area="<<rect.area()<<endl;
private:
int width, height;
public: cout<<"area="<<rectb.area();
rectangle( );
int area(); getch();
};
rectangle::rectangle( ) }
{

width=3;
height=4;
}
int rectangle:: area()
{

return width*height;
}
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 9
Practice Question:

• Write a class that contains two integer data


members which are initialized to 100 and 200
respectively, when an object is created.
• It has member function “avg” that displays
average of data members.

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 10
OBJECT ORIENTED PROGRAMMING(CS-1202)

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 1
Types of Constructor

• To reserve memory for a newly instantiated


object, there are three basic kinds of
constructor.

• The default constructor

• Parameterized constructor

• The copy constructor


C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 2
1. The default constructor:
• The default constructor takes no parameter
and performs no processing other than the
reservation of memory.

• If no constructor are available for a class, the


compiler implicitly creates a default
parameter less constructor and has a null
body.

• It will always be called by the compiler if no


user defined constructor is provided.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 3
Syntax:

• class constructor
{
constructor( )
{
// body of constructor
}
}

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 4
Example:

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 5
2. Parameterized Constructor:
• The method of passing parameter to a constructor is
same as passing parameter to normal function.

• The only difference is that the parameters are passed


to the constructor when the object is declared.

• It is possible to pass one or more arguments to a


constructor function.

• Simply add the appropriate parameters to the


constructor function’s declaration and definition.
Then, when you declare an object, specify the
arguments.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 6
Syntax:

• class constructor
{
constructor(parameters )
{
// body of constructor
}
}

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 7
Example

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 8
Example:
#include<iostream> int _tmain(int argc, _TCHAR* argv[])
#include<conio.h> {
usingnamespace std;
circle cir(9);
class circle
{
private: .
cout<<"circumference = \t"<<cir circum();
int radius;
public: getch();
circle(int r) return 0;
{ }
radius=r;
}
int circum()
{
return 2*3.14*radius;
}
};

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 9
Example
#include<iostream> int main()
#include<conio.h> {
usingnamespace std;
int x,y;
class rectangle
{ cin>>x>>y;
private:
int width, height; rectangle rect(x,y);
public:
rectangle(int a, int b) cout<<rect.area();
{
return 0;
width=a;
height=b; }
}

int area()
{

return width*height;
}
};
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 10
Practice Question
• Define a class HOTEL in C++ with the following description:

• Private Members
• · RNo //Data Member to store Room No
• · Name //Data Member to store customer Name
• · Tariff //Data Member to store per day charge
• · NOD //Data Member to store Number of days

• Public Members:
• · A parameterized constructor function to initialize data members
• · CALC( ) //A function to calculate and return amount as NOD*Tariff
• · Checkout( ) //A function to display Rno, Name, Tariff, NOD and Amount
(Amount to be displayed by calling function CALC( )

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 11
OBJECT ORIENTED PROGRAMMING(CS-1202)

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 1
Copy Constructor
• A copy constructor is a special constructor for
creating a new object as a copy of an existing object.

• Copy constructors are used when Initializing an


object at the time of creation (we want to create an
object with state of a pre existing object)

• There are two types of copy constructor


− Default copy constructor
− User defined copy constructor

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 2
Default Copy Constructor

• The default copy constructor can be used on


any object without being explicitly defined.

• Its name is “default copy constructor”


because it is available by default in all
classes.

• The user does not need to write this


constructor.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 3
Syntax
• Default constructor accepts a single object of
same type as parameter.
• The parameter for default constructor can be
given in parenthesis or using assignment
operator.
• Syntax:
• class_name object_name(parameter_object);
• Or
• class_name object_name=parameter_object;

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 4
Syntax:

• class_name: It is the name of class and indicates


the type of object to be created.
• Object_name: It indicates the name of object to be
created
• Parameter_object: It indicates the name of object
that is passed to default constructor, the values of
data members of parameter object are copied to data
members of new object.
• The type of new object and parameter object must be
same.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 5
Example:

}
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 6
Example:
• #include <iostream>
int main(int argc, char** argv) {
• #include<conio.h>
Marks obj(10,20);
• using namespace std;
• class Marks
Marks obj2=obj; //copy constructor
• {
• private:
obj.display();
• int maths, science;
• public:
• Marks(int m, int s)
obj2.display();
• {
• maths=m; return 0;
• science=s; }
}
• void display()
• {
• cout<<"Maths="<<maths<<endl;
• cout<<"Science="<<science<<endl;
• }
• };
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 7
OBJECT ORIENTED PROGRAMMING(CS-1202)

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 1
Passing Parameters to Functions:

• There are two most popular ways to pass


parameters.

• Passing parameters by value

• Passing parameters by reference

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 2
Passing Parameters by Value

• In this parameter passing method, values of


actual parameters are copied to function’s
formal parameters and the two types of
parameters are stored in different memory
locations.

• So any changes made inside functions are


not reflected in actual parameters of caller.

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 3
Example
For example. in the below code, value of x is modified
using the function fun().

#include <iostream>
using namespace std;

void fun(int x) {
x = 30;
} Output:
x = 20

int main() {
int x = 20;
fun(x);
cout << "x = " << x;
return 0;
}
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 4
Pass by Reference

• Both actual and formal parameters refer to


same locations, so any changes made inside
the function are actually reflected in actual
parameters of caller.

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 5
Example
#include <iostream>
#include<conio.h>
using namespace std;

void fun(int x, int &y)


{
x=x*2;
y=y*2;
}

int main(int argc, char** argv) {


int a,b;
cout<<"Enter two integer values for a and b";
cin>>a>>b;
cout<<endl<<"The values before function call= "<<a<<"\t"<<b<<"\n";
fun(a,b);
cout<<"The value after function call= "<<a<<"\t\t"<<b<<"\n";
return 0;
} C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 6
User Defined Copy Constructor

• It is possible to create our own copy of


constructor defined by the fact that takes a
reference to an object of same class as a
function argument.
• Syntax:
− ClassName (const className &old_obj);
• A copy constructor will usually access the
attribute values of the parameter object
using the dot operator.

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 7
Example:
• class Marks
• { int main(int argc, char** argv) {
• private:
• int maths, science; Marks obj(10,20);
• public:
• Marks(int m, int s) Marks obj2(obj).; //copy constructor
• {
• maths=m;
• science=s;
obj.display();
}
obj2.display();
• Marks(const Marks & o)
• {
• maths=o.maths;
return 0;
• science=o.science }
• }
• void display()
• {
• cout<<"Maths="<<maths<<endl;
• cout<<"Science="<<science<<endl;
• }
• };

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 8
• All member values of one object can be
assigned to other object using copy
constructor.

• For copying the object values both objects


must belong to the same class.

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 9
OBJECT ORIENTED PROGRAMMING(CS-1202)

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 1
Function Overloading
• The process of declaring multiple functions with same
name but different parameters is called function
overloading.

• When two or more functions share the same name,


they are said overloaded.

• The function with same name must differ in one of


the following ways.
• Number of parameters
• Type of parameter
• Sequence of parameters
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 2
Function Overloading
• Function overloading allows programmer to assign
same name to all functions with similar tasks.
• It helps the user in using different functions easily.
• The user does not need to remember many names
for similar types of tasks.
• For example the programmer can declare the
following functions to calculate average:
• float Average(int, int);
• float Average(int, float);
• float Average(float, int);

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 3
• The user can use same name and pass
different types of parameters.

• When the user calls the function the compiler


checks the parameters and their types.

• The corresponding function is executed


according to the types, number and sequence
of parameters in function call
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 4
Example
These functions having the same name but different arguments are known
as overloaded functions. For example:

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 5
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 6
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 7
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 8
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 9
Output

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 10
Constructor overloading
• In C++, We can have more than one constructor in a class with
same name, as long as each has a different list of arguments.
• This concept is known as Constructor Overloading and is quite
similar to function overloading.
• Overloaded constructors essentially have the same name .The
constructors with same name must differ in one of the following
ways.
• Number of parameters
• Type of parameter
• Sequence of parameters
• A constructor is called depending upon the number and type of
arguments passed.
• While creating the object, arguments must be passed to let
compiler know, which constructor needs to be called.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 11
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 12
Example

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 13
Example
#include<conio.h>
#include<iostream>
Using namespace std;

class sum
{
public:
sum(int l,int m, int n)
{
cout<<"sum of 3 integers is
="<<(l+m+n)<<endl;
}
sum(int l,int m)
{

cout<<"sum of 2 integers is
="<<(l+m)<<endl;
}
};
int main()
{
sum x(6,2),y(7,6,9);
return 0;
}

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 14
Example:

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 15
Practice Questions:
• Write three versions of a function “line”. The first version takes no
parameter and displays a line of 10 asterisks. The second version takes an
integer parameter and displays a line of n asterisks. The third version
takes an integer and a character as parameters and displays a line of given
character of n length.

• Create a class named 'Rectangle' with two data members- length and
breadth and a function to calculate the area which is 'length*breadth'. The
class has three constructors which are :
1 - having no parameter - values of both length and breadth are assigned
zero.
2 - having two numbers as parameters - the two numbers are assigned as
length and breadth respectively.
3 - having one number as parameter - both length and breadth are
assigned that number.
Now, create objects of the 'Rectangle' class having none, one and two
parameters and print their areas.

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 16
OBJECT ORIENTED PROGRAMMING(CS-1201)

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 1
Lifetime of Object
• Lifetime is defined as time between creation and
destruction of object.

• Based on persistence and visibility, objects are


divided into four types.

• Persistence is the lifetime of variable which shows


how long does an object last.

• Visibility of a variable determines how much of the


rest of program can access an object. Another word
for visibility is scope.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 2
• Some objects may exist throughout the running of a
program and may be visible in all modules.

• Other objects may exist momentarily within the


limited scope of a particular method or statement
body.

• Between these two extremes we may have range of


lifetimes and visibility among instantiated objects.

• On the basis of these ranges of persistence and


visibility objects are divided into four types.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 3
1. Automatic / Local Objects
• An automatic object is instantiated within the scope of
part of a program module.
• Automatic objects are declared inside the scope of
pair of braces.
• Automatic objects are automatically destroyed when
they fall out of scope in which they were instantiated.
• e.g
• int main( )
{
rectangle rect;
// statements;
}
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 4
• The following object is automatic because it is
declared inside the body of main function.

• It will be visible/ accessible any where inside


main and persist until main finished.

• // keyword “auto” may be used but it is


optional.

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 5
Example
#include<iostream.h>
#include<conio.h> int main()
class student {
{
private: student st; //local object
int rn;
float fees;
st.readdata();
public: st.writedata();
void readdata() getch();
{ return 0;;
cout<<"Enter the rollno. and fees of the student"; }
cin>>rn>>fees;
}
void writedata()
{
cout<<"The rollno. is "<<rn<<endl;
cout<<"The fees is "<<fees<<endl;
}
};

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 6
2.External/ Global Objects
• External objects are persistent throughout the lifetime
of a program and having file scope.
• Their visibility is throughout the module source file.
• Declaration: An external object is declared outside
the scope of any braces.
• rectangle rect; //outside main function exist globally
• {
• // statements;
• }

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 7
• The main reason of external objects would be to
make the object visible in other source files which are
in the same system.

• Since only externally declared objects can be


referenced in other program modules.

• We can declare global objects in a separate file and


can make that file a header file.

• Then we can include that header file in source file in


which we need that global object.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 8
3.Static Objects
• We have seen that global objects are persistent and
visible throughout lifetime of a program whereas
automatic objects are visible within the scope in which
they are declared.
• There is also a possibility in c++ to explicitly declare a
variable or object which has the scope of an automatic
object but life time of an external or global object.
• This is known as static object.
• Example:
• Void function
• {
• rectangle rect;
• static rectangle rect; }
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 9
• Example Program to implement Local,
Global and Static Objects:

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 10
Header File
• #include<iostream>
• using namespace std;
• class a
• {
• int marks;
• public:
• a()
• {
• marks=11;

• }
• void ut()
• {
• cout<<marks;
• }
• };

• a obj;

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 11
#include"a.h" int main(){
#include<conio.h>
#include<iostream> for(int i=0;i<=2;i++)
using namespace std; { bb o;
class bb static bb o2;
{ cout<<"local object value";
int mar; o.get(5);
int n; o.show();
public: cout<<"static object value";
bb() o2.get(10);
o2.show();
{ cout<<"global object value";
n=0; go.get(7);
go.show();
} }
void get(int x)
{ cout<<"External object value"<<endl;
n=x+n; obj.ut();
}
void show( ) getch();

{ return 0;
cout<<endl<<n<<endl; }
}
};
bb go;
12
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 13
OBJECT ORIENTED PROGRAMMING(CS-1201)

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 1
Pointers:
• The variables that are used to hold the memory address of
another variable is called a pointer variable
• The data type of the variable (whose address a pointer is to
hold) and the pointer variable must be same.
• Declaration Syntax:
• A pointer variable is declared by placing an asterisk(*) after data
type or before the variable name in declaration statement.
• Datatype * variable name;
• E.g. if a pointer variable “P” is to hold the memory address of an
integer variable it is declared as:
• int *P
• Similarly if a pointer variable is to hold memory address of a
floating point variable, it is declared as
• float *a;
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 2
Pointer Operators:
• “*” and “&” are two special pointer operators.
• The “&” is unary operator that returns the memory address of its
operand.
• The second pointer operator “*” is the complement of &. It is the
unary operator that returns the value located at the address that
follows.
• E.g.
• int *x; // Pointer Declaration
• int a,b;
• a=10;
• x=&a; // Places address of “a” in x
• b=*x; // Places value at that address in b

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 3
Dynamic Memory
• Suppose you want to put a toy in a box, but you only have an approximate
idea of its size. For that, you would require a box whose size is equal to
the approximate size of the toy.

• We face a similar situation in C++ also when we want to input a sentence


as an array of characters but are not sure about the number of characters
in the array.

• Now, while declaring the character array, if we specify its size smaller than
the size of the input string, then we will get an error because the space in
the memory allocated to the array is lesser than the size of the input
string. This is the same case as trying to fit a big toy in a smaller box. If we
specify its size much larger than the size of the input string, then the array
will be allocated a space in the memory which is much larger than the size
of the input string, thus unnecessarily consuming more memory even
when it is not required. This is like putting a small toy in a large box.

• In the above case, we don't have the idea about the size of the array until
the string is input by the user.
4
Dynamic Objects:
• Dynamic objects are used when the object to be
created is not predictable enough.
• This is usually when we cannot determine at compile
time
• Object identities
• Object qualities
• Object lifetimes
• Dynamic objects use dynamic memory allocation
• Dynamic objects can be created and destroyed at run
time
• In C++ a pointer can be directed to an area of
dynamically allocate memory at run time
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 5
The new operator
• The dynamically created objects are just like any
other object.
• When it is created its constructor is called.
• We can allocate and de allocate objects dynamically
using “new” and “delete” operators respectively.
• new
• The new operator is used to allocate memory at
runtime.
• Syntax: Classname *fp = new Classname;
• If you write A * a = new A() the default constructor of
the class A is called and it dynamically allocates
memory for one object of the class A and the address
of the memory allocated is assigned to the pointer a. 6
The delete Operator
• The delete operator is used to deallocate the memory
created by new operator at runtime. Once the
memory is no longer needed it should be free so that
the memory becomes available again for other
request of dynamic memory.
• Syntax:
• delete pointer-variable;
• In the delete operator the pointer-variable is the
pointer that points to the data object created by the
new.
• delete fp;
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 7
Destructor:

• A destructor is a special member function that works just


opposite to constructor, unlike constructors that are used for
initializing an object, destructors destroy (or delete) the object.
• Syntax of Destructor

• ~class_name()
• {
• //Some code
• }

• Similar to constructor, the destructor name should exactly match


with the class name. A destructor declaration should always
begin with the tilde(~) symbol as shown in the syntax above.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 8
When does the destructor get called?
• A destructor is automatically called when:
• The program finished execution.
• When a scope (the { } parenthesis) containing local
variable ends.
• When you call the delete operator.
• Destructor rules
• Name should begin with tilde sign(~) and must match class
name.
• There cannot be more than one destructor in a class.
• Unlike constructors that can have parameters, destructors do not
allow any parameter.
• They do not have any return type, just like constructors.
• When you do not specify any destructor in a class, compiler
generates a default destructor and inserts it into your code.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 9
Example:
• include <iostream>
• using namespace std;
• class HelloWorld{
• public:
• //Constructor
• HelloWorld(){
• cout<<"Constructor is called"<<endl;
• }
• //Destructor
• ~HelloWorld(){
• cout<<"Destructor is called"<<endl; OUTPUT
• }
• //Member function
• void display(){
• cout<<"Hello World!"<<endl;
• }
• };

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 10
OBJECT ORIENTED PROGRAMMING(CS-1201)

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 1
Passing Object as an Argument
• Object can also be passed as argument to member
functions.
• When an object is passed as argument to a member
function only the name of the object is written in the
argument list.
• The number of parameters and their types must be
defined in the member function to which the object is
to be passed.
• The objects that are passed are treated local for the
member functions and are destroyed when the
control returns to the calling function.

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 2
Syntax:

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 3
Example:
• #include <iostream>
• using namespace std;

• class Example {
• public:
• int a;

• // This function will take
• // an object as an argument

• void add(Example E)
• {
• a = a + E.a;
• }

• };

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 4
Output:

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 5
Example 2:

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 6
Output:

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 7
Returning Object From a Member
Function
• The method of returning an object from member function is
same as returning a variable
• If a member function returns an object its return type should bee
same as the type of object to be returned.

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 8
Example:
• #include <iostream>
• using namespace std;

• class Example {
• public:
• int a;

• // This function will take
• // object as arguments and
• // return object
• Example add(Example Ea, Example Eb)
• {
• Example Ec;
• Ec.a = Ea.a + Eb.a;

• // returning the object
• return Ec;
• }
• };
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 9
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 10
Practice Question:

• Write a C++ program to add two complex


numbers by passing objects to a function. The
sum of complex numbers (object) should be
returned to the main() function and displayed.

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 11
OBJECT ORIENTED PROGRAMMING(CS-1201)

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 1
Friend Function
• A friend function can access members of class in
which it is declared.
• A friend function of a class is defined outside that
class' scope but it has the right to access all private
and protected members of the class.
• Even though the prototypes for friend functions
appear in the class definition, friends are not member
functions.
• A friend can be a function or member function, or a
class in which case the entire class and all of its
members are friends.

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 2
Syntax to Declare Friend Function
• To declare a function as a friend of a class, precede
the function prototype in the class definition with
keyword friend.

• A friend function is declared inside the class with


a friend keyword preceding as shown below.

• class className
• { ……
• friend returnType functionName(arg list);
• }

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 3
Some Points to Remember
• There are some points to remember while implementing
friend functions in our program:
• A friend function can be declared in the private or public section
of the class.
• It can be called like a normal function without using the object.
• A friend function is not in the scope of the class, of which it is a
friend.
• A friend function is not invoked using the class object as it is not
in the scope of the class.
• A friend function cannot access the private and protected data
members of the class directly. It needs to make use of a class
object and then access the members using the dot operator.
• A friend function can be a global function or a member of
another class.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 4
Example 1
• #include<conio.h>
• #include<iostream>
• Using namespace std;

class a
• {
• private:
• int i,j;
• public:
• void setvalues(int x,int y)
• {
• i=x;
• j=y;
• }
• friend void sum(a);
• };
• void sum(a o)
• {
• cout<< “sum = ” <<o.i+o.j;
• }

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 5
Example 2:. Write a program to implement
“Friend Function” for different classes.

#include<iostream> class b
usingnamespace std; { int sum(a o,b o1)
private: {
class b; int j; return o.i+o1.j;
class a public: }
{ void setvalues(int y)
private: { void main()
int i; j=y; {
public: } a obj;
void setvalues(int x) friend int sum(a,b); b obj1;
{ }; obj.setvalues(7);
i=x; obj1.setvalues(8);
} cout<<"sum = "<<sum(obj,obj1);
friend int sum(a,b); getch();
}; }

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 6
Practice Question:

• Write a program to find out maximum out of


two numbers using friend function.
• Note: here one number is member of one
class and other number is member of another
class

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 7
OBJECT ORIENTED PROGRAMMING(CS-1201)

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 1
Operator Overloading
• The process of defining additional meanings of
operators is known as operator overloading.
• It enables an operator to perform operations depending
on the type of operands.
• It also enables the operators to process user defined
data types.
• The basic arithmetic operators such as +,-,* and /
normally work with basic data types such as int, float
and long etc.
• The application of these operators with basic data types
are already defined in the language.
• However an error will occur if these operators are used
with user defined data types.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 2
Example
• The addition operator is used to add two numeric values.
Suppose a, b and c are three integer variables. The
following statement will add the contents of a and b and
store the result in variable c.
• c=a+b;

• The addition operator already knows how to process


integer operands. But it does not know how to process two
user defined data objects.

• The above statement will generate error if a , b abd c are


objects of a class. However operator overloading can
enable the addition operator to manipulate two objects.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 3
Overloading an Operator
• An operator can be overloaded by declaring a special
member function in the class.
• The member function uses the keyword operator with
the symbol of operator to be overloaded.
• Syntax:

• The Syntax of overloading an operator is as follows:

− return_type operator op( )


− {
− function body;
− }
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 4
Syntax:
• return_type: it indicates the value returned by the
member function.
• operator: it is the keyword that indicates that the
member function is used to overload an operator.
• op:It is the symbol of operator to be overloaded.

• Example:
• void operator++( )
• {
Function body;
• }

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 5
Overloading Unary Operators
• A type of operator that works with single
operand is called unary operator.

• The unary operators are overloaded to


increase their capabilities.

• The operators that can be overloaded in C++


are as follows.

• + , - , *, ++, -- etc.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 6
Overloading ++ Operator
• The increment operator ++ is a unary operator. It
works with single operand. It increases the value
of operand by 1.

• It only works with numerical values by default.

• It can be overloaded to enable it to increase the


values of data members of an object in the same
way.

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 7
Example Program:
class count int main( )
{ {
private: count obj;
int n,m; cout<<"Values before increment"<<endl;
public: obj.show( );
count( )
{ ++obj;
n=0; cout<<"Values after increment"<<endl;
m=1; obj.show();
} getch( );
void operator++( ) return 0;
{ }
n=n+1;
m=m+1;
}
void show( )
{
cout<<"n ="<<n<<endl;
cout<<"m ="<<m<<endl;
}
};

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 8
Overloading Postfix Increment
Operator
class count int main( )
{ {
private: count obj;
int n,m; cout<<"Values before increment"<<endl;
public: obj.show( );
count( )
{ obj++;
n=0;
m=1; cout<<"Values after increment"<<endl;
} obj.show();
void show( ) getch( );
{ return 0;
cout<<"n ="<<n<<endl; The keyword }
cout<<"m ="<<m<<endl;
} “int” in
void operator++( int) following
{ statement
n=n+1;
indicates that
m=m+1; operator is
`} overloaded
}; for postfix
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 9
Practical Question:

• Overloaded negative operator (-) to negate


values of an object.

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 10
OBJECT ORIENTED PROGRAMMING(CS-1201)

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 1
Composition
• In real-life, complex objects are often built from smaller, simpler
objects. For example, a car is built using a metal frame, an engine,
some tires, a transmission, a steering wheel, and a large number of
other parts.
• A personal computer is built from a CPU, a motherboard, some
memory, etc…
• Even you are built from smaller parts: you have a head, a body, some
legs, arms, and so on. This process of building complex objects from
simpler ones is called object composition
• . Broadly speaking, object composition models a “has-a” relationship
between two objects.
• A car “has-a” transmission. Your computer “has-a” CPU. You “have-a”
heart.
• The complex object is sometimes called the whole, or the parent. The
simpler object is often called the part, child, or component.

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 2
Composition Continued…
• In a composition relationship, the object of whole is responsible for the
existence of the parts. Most often, this means the part is created when
the object is created, and destroyed when the object is destroyed.

• But more broadly, it means the object manages the part’s lifetime in
such a way that the user of the object does not need to get involved.
For example, when a body is created, the heart is created too. When a
person’s body is destroyed, their heart is destroyed too. Because of
this, composition is sometimes called a “death relationship”.

• Object Composition is useful in a C++ context because it allows us to


create complex classes by combining simpler, more easily manageable
parts.

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 3
Composition Continued…

• Composition is generally used when you want the features of an


existing class inside your new class, but not its interface. That
is, you embed an object to implement features of your new
class, but the user of your new class sees the interface you’ve
defined rather than the interface from the original class.

• You simply create objects of your existing class inside the new
class. This is called composition because the new class is
composed of objects of existing classes.

• This reduces complexity, and allows us to write code faster and


with less errors because we can reuse code that has already
been written, tested, and verified as working.

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 4
Syntax:

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 5
Example

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 6
Example Program:
#include "stdafx.h" class B class C
#include <iostream> { {
#include<conio.h> int d,e;
public: A o;
using namespace std; int c; B ob;
class A B() public:
{ { C( )
int a,b; c=5; {
public: } d=6;
A() void sho() e=7;
{ { }
a=2; cout<<endl<<c<<endl; void dis()
b=3; } {
} };
void show() cout<<"Data members of A = ";
{ o.show();
cout<<endl<<a<<"\n"<<b<< cout<<"Data members of B = ";
"\n"; ob.sho();
} cout<<"Data members of C = ";
}; cout<<endl<<d<<"\n"<<e;
}
};

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 7
Output:

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 8
Example Program
#include "stdafx.h" class B class C
#include <iostream> { {
#include<conio.h> int d,e;
public: A o;
using namespace std; int c; B ob;
class A B(int z) public:
{ { C(int t,int y,int q,int w,int
int a,b; c=z; s):o(q,w),ob(s)
public: } {
A(int x,int y) void sho() d=t;e=y;
{ { }
a=x;b=y; cout<<c<<"\n"; void dis()
} } {
void show() }; cout<<ob.c;
{ o.show();
cout<<a<<"\n"<<b<<"\n"; ob.sho();
} cout<<d<<"\n"<<e;
}; }
};

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 9
OBJECT ORIENTED PROGRAMMING(CS-1201)

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 1
Inheritance
• Inheritance is an important feature of the object
oriented programming.

• In inheritance the code of existing classes is used for


making new classes.

• This saves time for writing and debugging the entire


code for a new class .
• To inherit means to receive.

• In inheritance a new class is written such a way that it


can access or use the members of an existing class.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 2
Derived Class & Base Class
• Derived Class
The new class that can access the
members of an existing class is called the
derived class or child class.

• Base Class:
The existing class that is inherited is
called base class or parent class.

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 3
Example
• we have a class Shape which is a base class for two class class
Rectangle and class Triangle. In inheritance, derived classes derived
from base class acquire all the features of the base class with its own
other features.
• According these details lets see a pictorial example of Inheritance in
C++ :-

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 4
Single Inheritance:
• In single inheritance the new class is derived
from only one base class.
• Syntax:

• Where access-specifier is one of public,


protected, or private, and base-class is the name of
a previously defined class

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 5
Protected Members:

• The protected members of base class fall between


private and public members.
• The private members are accessible by only the
member functions and friend functions of that class.
• While
• The protected members are accessible by the member
functions and friend functions of that class and also by
members of its derived class.
• Protected members are private for rest of the
program(except for the class in which they are
declared and derived class).
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 6
Types of Inheritance:

• Public Inheritance
• Protected Inheritance
• Private Inheritance

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 7
Public Inheritance:
• If base class is inherited as public, then the
base class protected members become the
protected members of derived class and
public members of base class become the
public members of derived class.
• Syntax:

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 8
Example Program1:
#include<conio.h> class Rectangle: public Shape Output:
#include<iostream> {
usingnamespace std; public:
int getArea()
{
// Base class return (width * height);
class Shape }
{ };
protected:
int width; int main( )
int height; {
Rectangle Rect;

public: Rect.setWidth(5);
void setWidth(int w) Rect.setHeight(7);
{
width = w; // Print the area of the object.
} cout << "Total area: " <<
void setHeight(int h) Rect.getArea() << endl;
{ return 0;
height = h; }
}
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 9
};
Example Program2:
#include<conio.h> class derived1: public base int main( )
#include<iostream> { {
usingnamespace std; // i & j are inherited as protected derived1 obj1;
int k; derived2 obj2;
// Base class
class base public:
{ void setk( )
obj1.set(2,3);
protected: {
int i, j; k=i*j; //legal obj1.show( );
void set (int a,int b) } obj1.setk( );
{ void showk( ) obj1.showk( );
i=a; {
j=b; cout<<k; }
} }; obj2.set(3,4);
void show( ) class derived2: public derived 1 obj2.show( );
{ { obj2.setk( );
cout<<i<<j; int m; obj2.showk( );
} obj2.setd( );
}; public: obj2.showd( );
void setd( )
{
m=i-j; // legal
} }
void showd( )
{
cout<<m; }
}; 10
• Object of derived1 can access public and
protected members of base class within its
own member functions.
• &
• Object of derived2 can access member
functions of derived2 + public and protected
members of base class and derived1 class.

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 11
OBJECT ORIENTED PROGRAMMING(CS-1201)

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 1
Private Inheritance
• If base class is inherited as private then all protected
and public members of base class will act as
private members of derived class.
• Public and protected members of base class will act
as private members of derived class which means
they would not be accessible by deived2 or outside
derived1.

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 2
Example Program
#include<conio.h> class derived1: private base
#include<iostream> {
usingnamespace std; // i & j are inherited as protected
int k;
// Base class
class base public:
{ void setk( )
protected: {
int i, j; k=i*j; // legal b/c I & j are private members to
public: derived class and can be used within
void set (int a,int b) derived class.
{ }
i=a; void showk( )
j=b; {
} cout<<k; }
void show( ) };
{
cout<<i<<j;
}
};

3
int main( )
{
derived1 obj;
illegal b/c set( ) & show( ) are
obj.set(2,3); private members of derived class
obj.show( ); and can not be accessed outside
derived class
obj.setk( );
obj.showk( );

} legal b/c setk( ) & showk( ) are


public members of derived class

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 4
Accessing Private Members
• Now private members can be accessed through public interface
of derived class.
#include<conio.h> class derived1: private base
#include<iostream> {
usingnamespace std; // i & j are inherited as protected
int k;
// Base class void Set(int a, int b) and void
class base public:
{ void setk( )
show( ) are public members of
protected: { base class but private
int i, j; set(10,20); members of derived class and
public: k=i*j; cannot be accessed outside
void set (int a,int b) } So
{ void showk( ) These private members are
i=a; { accessed in public functions
j=b; show( );
} cout<<k; }
so that we can call them from
void show( ) }; main function by calling setk( )
{ and sshowk( )
cout<<i<<j;
}
}; C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 5
• int main( )
• {
• derived obj; illegal because it is a private
• member of derive class
• obj.set(10,20);

• obj.setk( );
• obj.showk( ); Legal because both are
• public members
• }

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 6
Practice Question
• Write a class LocalPhone that contains an attribute phone to
store a local telephone number. The class contains member
functions to input and display phone number.
• Write a child class NatPhone for national phone numbers that
inherits LocPhone class. It additionally contains an attribute to
store city code. It also contains member functions to input and
show the city code.
• Write another class InPhone for international phone numbers
that inherits NaatPhone class. It additionally contains an
attribute to store country code. It also contains member
functions to input and show the country code.

• Output of the program should display country_code then


city_code then local phone number.

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 7
OBJECT ORIENTED PROGRAMMING(CS-1201)

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 1
Protected Inheritance
• If base class is inherited as protected then all
protected and public members of base class will act
as protected members of derived class.
• Syntax:

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 2
Example
#include<conio.h> class derived1: protected base
#include<iostream> {
usingnamespace std; // i & j are inherited as protected
int k;
// Base class
class base public:
{ void setk( )
protected: { Public and protected members
int i, j; set(10,20); of base class become
public: k=i*j;
void set (int a,int b) }
protected member of derived
{ void showk( ) class and except second
i=a; { derived class we can not
j=b; show( ); access protected members
} cout<<k; } outside the class.
void show( ) }; So we will access this
{ protected member through
cout<<i<<j;
}
public interface functions
}; Setk( ) and showk( )

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 3
• int main( )
• {
• derived1 obj; illegal because it is a
• protected member of derive
• obj.set(10,20); class

• obj.setk( );
• obj.showk( ); Legal because both are
• public members
• }

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 4
Example Program2:
#include<conio.h> class derived1: protected base int main( )
#include<iostream> { {
usingnamespace std; protected :
int k; derived2 obj2;
// Base class public:
class base void setk( )
obj2.setk( );
{ {
obj2.showk( );
protected: set(20,30);
int i, j; obj2.setd( );
k=i*j; //legal
void set (int a,int b) } obj2.showd( );
{ void showk( ) return 0;
i=a; {
j=b; cout<<k; } }
} };
void show( ) class derived2: public derived 1
{ {
cout<<i<<j; int m;
}
}; public:
void setd( )
{
set(10,20);
m=i-j; // legal
}
void showd( )
{
show( );
cout<<m; } }; 5
OBJECT ORIENTED PROGRAMMING(CS-1201)

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 1
Pointer to Objects
• The member of a class can be accessed
through the pointer to the class.
• The arrow symbol (->) is also known as
member access operator.
• It is denoted by a hyphen(-) and a greater than
sign (>).
• The general syntax to access a member of a
class through its pointer “P” is:
P -> class member;

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 2
Example:
#include<iostream> int main()
#include<conio.h> {
using namespace std; ptr * p;
ptr o;
class ptr p=&o;
{ p->input();
private: p->show();
char name[15]; getch();
int age; return 0;
public: }
void input()
{
cout<<"Enter Name & Age";
cin>>name>>age;
}
void show()
{
cout<<"Name="<<name<<endl;
cout<< "Age="<<age;
}
};

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 3
Pointer to Derived Types
• If a pointer object is defined to point to a class then it can
also point to any of its subclass.
• However, even if the pointer points to an object of its derived
class, it remains of base class type.
• Although we can use a base pointer to point to a derived
object, we can access only the members of the derived type
that were inherited from the base.
• That is, we won’t be able to access any member added by
the derived class.
• This is the default method of execution of a member function
through a pointer.
• A pointer of derived type may not point to base type
object.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 4
Example
include<iostream> int main()
#include<conio.h>
using namespace std;
{
base *bp;
class base
{ derived d;
int i;
public:
void set(int num) bp=&d; // base pointer points to derived object
{
i=num; bp->set(10); // accessing derived object using base pointer
}
int get()
{ cout<<bp->get(); // accessing only members of derived type that
return i; were inherited from the base
}
};
class derived: public base bp->set(d10); // Error
{
int j; cout<<bp->getd(); //Error
public:
void setd(int num)
return 0;
{ }
j=num;
}
int getd()
{
return j;
}
};
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 5
OBJECT ORIENTED PROGRAMMING(CS-1201)

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 1
Early Binding
• The events that take place at the compile time are called early
binding.
• It is also called static binding.
• In essence , early binding occurs when all the information needed
to call a function is known at the compile time.
• Accessing member functions of class through the pointer is an
example of early binding.
• In the previous example the compiler decides at compile time to
always execute the member function of the class whose type
matches the type of pointer irrespective of the contents of the
pointer.
• Thus whatever the object points to during execution of the
program, the pointer always access the member of the class
whose type matches with its type.

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 2
Polymorphism
• Poly means many and morphism means forms
or shapes.

• In polymorphism the member functions with the


same name are defined in each derived class
and also in base class.

• Polymorphism therefore is the ability for objects


of different classes related by inheritance to
response differently to same function call
• C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 3
Virtual Functions

• Polymorphism is achieved by means of virtual


functions.
• Definition:
• A virtual function is a member function of class that is
declared and defined within a base class and may be
redefined in any class derived from this base class.
• Its name in the base class and in the derived classes
remain the same. The definition in these cases may
be different.
• The virtual function in derived class is executed
through the pointer of base class.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 4
Syntax of Declaration of Virtual
Functions
• Keyword virtual is used before function declaration in
base class.

• virtual return_type function_name(parameters);

• The use of word virtual before function declaration in


derived classes is optional.

• Once a function is declared it becomes virtual in all


derived classes, even when the keyword virtual is not
written.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 5
Function Overriding
• When a virtual function is redefined then all of
its prototype must be the same.
• The term overriding refers to the redefinition of
a virtual function by a derived class.
• Function return type, name, type of parameters
and number of parameters should be same.

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 6
Example
#include<conio.h> class derived : public base { int main()
#include <iostream> public: {
using namespace std; void print() base* bptr;
{ derived d;
class base { cout << "print derived bptr = &d;
public: class" << endl;
virtual void print() } // virtual function, binded at
{ runtime
cout << "print base void show() bptr->print();
class" << endl; {
} cout << "show derived // Non-virtual function,
class" << endl; binded at compile time
void show() } bptr->show();
{ };
cout << "show base getch();
class" << endl; return 0;
} }
};

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 7
Practice Question
• Create a base class called shape. Use this class to store two double type
values that could be used to compute the area of figures.
• Derive two specific classes called triangle and rectangle from the base
shape. Add to the base class, a member function get_data ( ) to initialize
base class data members and another member function display_area ( ) to
compute and display the area of figures.
• Make display area ( ) as a virtual function and redefine this function in
the derived classes to suit their requirements.
• Using these three classes, design a program that will accept dimensions
of a triangle or a rectangle interactively and display the area. Remember
the two values given as input will be treated as lengths of two sides in
the case of rectangles and as base and height in the case of triangles and
used as follows:
• Area of rectangle = x * y
• Area of triangle = ½ * x * y

C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 8

You might also like