Classes and Objects: C++ Class Definitions
Classes and Objects: C++ Class Definitions
The main purpose of C++ programming is to add object orientation to the C programming
language and classes are the central feature of C++ that supports object-oriented
programming and are often called user-defined types.
A class is used to specify the form of an object and it combines data representation and
methods for manipulating that data into one neat package. The data and functions within
a class are called members of the class.
A class definition starts with the keyword class followed by the class name; and the class
body, enclosed by a pair of curly braces. A class definition must be followed either by a
semicolon or a list of declarations. For example, we define the Box data type using the
keyword class as follows:
class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
The keyword public determines the access attributes of the members of the class that
follows it. A public member can be accessed from outside the class anywhere within the
scope of the class object. You can also specify the members of a class as private or
protected which we will discuss in a sub-section.
Both of the objects Box1 and Box2 will have their own copy of data members.
145
C++
The public data members of objects of a class can be accessed using the direct member
access operator (.). Let us try the following example to make the things clear:
#include <iostream>
class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main( )
{
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
return 0;
146
C++
When the above code is compiled and executed, it produces the following result:
It is important to note that private and protected members cannot be accessed directly
using direct member access operator (.). We will learn how private and protected members
can be accessed.
Concept Description
C++ inline functions With an inline function, the compiler tries to expand
the code in the body of the function in place of a call
to the function.
The this pointer in C++ Every object has a special pointer this which points
to the object itself.
147
C++
Pointer to C++ classes A pointer to a class is done exactly the same way a
pointer to a structure is. In fact a class is really just
a structure with functions in it.
Static members of a class Both data members and function members of a class
can be declared as static.
Let us take previously defined class to access the members of the class using a member
function instead of directly accessing them:
class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
double getVolume(void);// Returns box volume
};
Member functions can be defined within the class definition or separately using scope
resolution operator, ::. Defining a member function within the class definition declares
the function inline, even if you do not use the inline specifier. So either you can
defineVolume() function as below:
class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
double getVolume(void)
{
return length * breadth * height;
}
148
C++
};
If you like, you can define the same function outside the class using the scope resolution
operator (::) as follows:
double Box::getVolume(void)
{
return length * breadth * height;
}
Here, only important point is that you would have to use class name just before ::
operator. A member function will be called using a dot operator (.) on a object where it
will manipulate data related to that object only as follows:
Let us put above concepts to set and get the value of different class members in a class:
#include <iostream>
class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
149
C++
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
150
C++
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
A class can have multiple public, protected, or private labeled sections. Each section
remains in effect until either another section label or the closing right brace of the class
body is seen. The default access for members and classes is private.
class Base {
public:
protected:
private:
};
151
C++
#include <iostream>
class Line
{
public:
double length;
void setLength( double len );
double getLength( void );
};
When the above code is compiled and executed, it produces the following result:
Length of line : 6
Length of line : 10
By default all the members of a class would be private, for example in the following
classwidth is a private member, which means until you label a member, it will be assumed
a private member:
class Box
{
double width;
public:
double length;
void setWidth( double wid );
double getWidth( void );
};
Practically, we define data in private section and related functions in public section so that
they can be called from outside of the class as shown in the following program.
#include <iostream>
class Box
{
public:
double length;
void setWidth( double wid );
double getWidth( void );
153
C++
private:
double width;
};
return 0;
}
When the above code is compiled and executed, it produces the following result:
Length of box : 10
Width of box : 10
154
C++
You will learn derived classes and inheritance in next chapter. For now you can check
following example where I have derived one child class SmallBox from a parent class Box.
Following example is similar to above example and here width member will be accessible
by any member function of its derived class SmallBox.
#include <iostream>
using namespace std;
class Box
{
protected:
double width;
};
155
C++
{
SmallBox box;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Width of box : 5
A constructor will have exact same name as the class and it does not have any return type
at all, not even void. Constructors can be very useful for setting initial values for certain
member variables.
#include <iostream>
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor
private:
double length;
};
{
cout << "Object is being created" << endl;
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
Parameterized Constructor
A default constructor does not have any parameter, but if you need, a constructor can
have parameters. This helps you to assign initial value to an object at the time of its
creation as shown in the following example:
#include <iostream>
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(double len); // This is the constructor
private:
double length;
};
return 0;
}
When the above code is compiled and executed, it produces the following result:
If for a class C, you have multiple fields X, Y, Z, etc., to be initialized, then use can use
same syntax and separate the fields by comma as follows:
A destructor will have exact same name as the class prefixed with a tilde (~) and it can
neither return a value nor can it take any parameters. Destructor can be very useful for
159
C++
releasing resources before coming out of the program like closing files, releasing memories
etc.
#include <iostream>
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor declaration
~Line(); // This is the destructor: declaration
private:
double length;
};
}
// Main function for the program
int main( )
{
Line line;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Copy Constructor
The copy constructor is a constructor which creates an object by initializing it with an
object of the same class, which has been created previously. The copy constructor is used
to:
If a copy constructor is not defined in a class, the compiler itself defines one.If the class
has pointer variables and has some dynamic memory allocations, then it is a must to have
a copy constructor. The most common form of copy constructor is shown here:
Here, obj is a reference to an object that is being used to initialize another object.
#include <iostream>
161
C++
class Line
{
public:
int getLength( void );
Line( int len ); // simple constructor
Line( const Line &obj); // copy constructor
~Line(); // destructor
private:
int *ptr;
};
Line::~Line(void)
{
cout << "Freeing memory!" << endl;
delete ptr;
}
int Line::getLength( void )
162
C++
{
return *ptr;
}
display(line);
return 0;
}
When the above code is compiled and executed, it produces the following result:
Let us see the same example but with a small change to create another object using
existing object of the same type:
#include <iostream>
class Line
{
public:
int getLength( void );
Line( int len ); // simple constructor
163
C++
private:
int *ptr;
};
Line::~Line(void)
{
cout << "Freeing memory!" << endl;
delete ptr;
}
int Line::getLength( void )
{
return *ptr;
}
display(line1);
display(line2);
return 0;
}
When the above code is compiled and executed, it produces the following result:
Friend Functions
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.
To declare a function as a friend of a class, precede the function prototype in the class
definition with keyword friend as follows:
class Box
{
double width;
165
C++
public:
double length;
friend void printWidth( Box box );
void setWidth( double wid );
};
To declare all member functions of class ClassTwo as friends of class ClassOne, place a
following declaration in the definition of class ClassOne:
#include <iostream>
class Box
{
double width;
public:
friend void printWidth( Box box );
void setWidth( double wid );
};
166
C++
return 0;
}
When the above code is compiled and executed, it produces the following result:
Width of box : 10
Inline Functions
C++ inline function is powerful concept that is commonly used with classes. If a function
is inline, the compiler places a copy of the code of that function at each point where the
function is called at compile time.
Any change to an inline function could require all clients of the function to be recompiled
because compiler would need to replace all the code once again otherwise it will continue
with old functionality.
To inline a function, place the keyword inline before the function name and define the
function before any calls are made to the function. The compiler can ignore the inline
qualifier in case defined function is more than a line.
A function definition in a class definition is an inline function definition, even without the
use of the inline specifier.
Following is an example, which makes use of inline function to return max of two numbers:
#include <iostream>
When the above code is compiled and executed, it produces the following result:
Max (20,10): 20
Max (0,200): 200
Max (100,1010): 1010
this Pointer
Every object in C++ has access to its own address through an important pointer
called thispointer. The this pointer is an implicit parameter to all member functions.
Therefore, inside a member function, this may be used to refer to the invoking object.
Friend functions do not have a this pointer, because friends are not members of a class.
Only member functions have a this pointer.
Let us try the following example to understand the concept of this pointer:
#include <iostream>
class Box
{
public:
// Constructor definition
Box(double l=2.0, double b=2.0, double h=2.0)
{
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
168
C++
}
double Volume()
{
return length * breadth * height;
}
int compare(Box box)
{
return this->Volume() > box.Volume();
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main(void)
{
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
if(Box1.compare(Box2))
{
cout << "Box2 is smaller than Box1" <<endl;
}
else
{
cout << "Box2 is equal to or larger than Box1" <<endl;
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
Constructor called.
Constructor called.
Box2 is equal to or larger than Box1
169
C++
Let us try the following example to understand the concept of pointer to a class:
#include <iostream>
class Box
{
public:
// Constructor definition
Box(double l=2.0, double b=2.0, double h=2.0)
{
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
}
double Volume()
{
return length * breadth * height;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main(void)
{
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
Box *ptrBox; // Declare pointer to a class.
170
C++
return 0;
}
When the above code is compiled and executed, it produces the following result:
Constructor called.
Constructor called.
Volume of Box1: 5.94
Volume of Box2: 102
A static member is shared by all objects of the class. All static data is initialized to zero
when the first object is created, if no other initialization is present. We can't put it in the
class definition but it can be initialized outside the class as done in the following example
by redeclaring the static variable, using the scope resolution operator :: to identify which
class it belongs to.
Let us try the following example to understand the concept of static data members:
#include <iostream>
class Box
{
171
C++
public:
static int objectCount;
// Constructor definition
Box(double l=2.0, double b=2.0, double h=2.0)
{
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
// Increase every time object is created
objectCount++;
}
double Volume()
{
return length * breadth * height;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main(void)
{
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
return 0;
}
When the above code is compiled and executed, it produces the following result:
172
C++
Constructor called.
Constructor called.
Total objects: 2
A static member function can only access static data member, other static member
functions and any other functions from outside the class.
Static member functions have a class scope and they do not have access to
the this pointer of the class. You could use a static member function to determine whether
some objects of the class have been created or not.
Let us try the following example to understand the concept of static function members:
#include <iostream>
class Box
{
public:
static int objectCount;
// Constructor definition
Box(double l=2.0, double b=2.0, double h=2.0)
{
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
// Increase every time object is created
objectCount++;
}
double Volume()
{
return length * breadth * height;
}
173
C++
int main(void)
{
return 0;
}
When the above code is compiled and executed, it produces the following result:
174