My Blog
Articles related to programming, computer science, technology and research.

29/08/2016 Categories: C++ Programming. Comments Off on Classes and Objects in C++



Object oriented programming paradigm makes it easy to solve real-world problems. Classes and objects are the fundamental concepts of object oriented paradigm. They make development of large and complex systems easier and help to produce software which is easy to understand, modular, modify, and reusable.


Syntactically structures and classes are similar. But a major difference between them is, by default all the members of a structure are public. Whereas, by default all the members of a class are private.


A rule of thumb is, use structures to store less amount of data and classes to store data as well as functions to process that data.


Class Declaration


A class is a template or blueprint for creating objects. Class is the basic mechanism to implement encapsulation. A class combines variables (data) and functions (behavior) into a single entity. By declaring a class we are creating a new user-defined type. Syntax for declaring a class is as follows:



In the above class declaration syntax class is a keyword which is used to declare classes. The body of the class starts with { and ends with };. A class can have variables and functions. These are together called as class members. Access specifier can be either public, private, or protected.


Private: All class members declared as private are only accessible within the class and are not accessible outside the class. Data hiding is implemented through private access specifier. By default access specifier for class members is private.


Public: All class members declared as public are accessible inside and outside the class.


Example for class declaration is as follows:



Function Definition


Inside Class


A function can be defined inside a class like we define functions in our C++ programs. Functions defined inside a class are by default treated as inline functions (provided they don’t contain any loops, switch, goto, static variables, or recursive code). An example of function defined inside the class is as follows:



Outside Class


Functions defined outside the class will contain scope resolution operator (::) to notify the compiler that this function belongs to a certain class.


Uses of scope resolution operator in a function definition are:

  • When a function with same name is available in different classes, this operator resolves the scope of a function to a certain class.
  • To restrict access to private data of a class to non-member functions.
  • Allows a member function of a class to call another member function of the same class without using dot operator.


Syntax of defining a function outside the class is as follows:



An example of defining a function outside the class is as follows:



Creating Objects


For using the classes that we declared in our programs, we need to create objects. An object is an instance of a class. The process of creating an object for a class in called as instantiation. Memory is only allocated for an object. Not to a class. Object creation syntax is as follows:


ClassName object-name;


Based on our student class example, objects can be created as follows:


Student std1, std2;


In the above example, std1 and std2 are objects of class Student.


Accessing Object Members


After creating an object, we can access the data and functions using the dot operator as shown below:


object-name.variable-name; (or)



Based on our student class example, we can access the get_details() function as shown below:





The complete program which demonstrates creating class, creating objects, and accessing object members is as follows:



In the above program class name is Student and object names are std1 and std2.


Nested Functions


A member function can call another member function directly without any need of dot operator. To call another member function, we can simply write the function name followed by parameter values enclosed in parentheses. An example for calling another member function is as follows:



In the above program, the function show_details() contains nested call to area() and peri() functions.


Inline Member Functions


Making a function inline avoids the overhead of a function call. By default functions defined inside a class are inline. To get the benefits of making a function inline, functions defined outside the class can also be made inline. Syntax for defining a function as inline is as follows:



Consider the following example which demonstrates inline member functions:



Memory Allocation for Classes and Objects


Class is not allocated any memory. This is partially true. The functions in a class are allocated memory which are shared by all the objects of a class. Only the data in a class is allocated memory when an object is created. Every object has its own memory for data (variables). For example consider the following Student class and its functions:



Now let’s create two objects for the above Student class as follows:


Student std1, std2;


Memory representation for the objects s1 and s2 will be as shown in the below diagram:




Static Members


C++ allows us to declare variables or functions as static members by using the keyword static.


Static Data


Syntax for declaring a static variable is as follows:


static data-type variable-name;


Static data members will have the following properties:

  • Only one copy of static data element will be created irrespective of the no. of objects created.
  • All objects share the same copy of the static data element.
  • All static data members are initialized to 0 when the first object for a class is created.
  • Static data members are only visible within the class. But their lifetime is throughout the program.


If needed, static data members can be accessed using the class name along with scope resolution operator. Let’s add a static member count to our Student class. The memory representation of two objects will be as shown below:




Student class with count static member is as follows:



Static Functions


Functions of a class can also be declared as static. Static functions have following properties:

  • It can access only static members declared in the same class.
  • As it is not part of an object, it is called using the class name along with scope resolution operator.
  • As static functions does not belong to a object, this pointer cannot be used with them.
  • A static function cannot be declared as a virtual function.
  • A static function can be declared with const, volatile type qualifiers.


Syntax for creating a static member function is as follows:



Syntax for accessing a static member function outside the class is as follows:



Following example demonstrates creating and using a static function:



Note: Two member functions cannot be declared with one function as static and another as non-static having the same name and same parameters list.


Static Objects


By default object data members contains garbage values. To initialize the data members to their default values, we can declare the objects as static. Syntax for creating static objects is as follows:


static ClassName object-name;


Below example demonstrates working with static objects:



In the above program, std1 and std2 are static objects. So all their data members like name, age, etc. will be initialized to their default values.


Array of Objects


As we can create array of basic data types, we can also create an array of user-defined types. An array of objects can be used to maintain details of a group of objects which are stored contiguously in memory. Syntax for creating an array of objects is as follows:


ClassName array-name[size];


For example we can create an array of objects for Student class which can be used to maintain details of a set of students. A single object in an array can be accessed using the subscript or index. Below program demonstrates the use of an array of objects:



Dynamic memory allocation for array of objects


In the previous topic memory for array of objects was static as the memory was allocated at compile time. To allocate memory dynamically or at run time, we use an array of pointers which can be created as follows:


ClassName *array-name[size];


Memory allocated for an array of pointers is far less than memory allocated for an array of objects. We can create an object at run time using the new operator as follows:


array-name[index] = new ClassName;


After dynamically allocating memory for an object we access the members using the -> operator as follows:




Below example demonstrates how to dynamically allocate memory for an array of objects:



Objects As Function Arguments


Like variables, objects can also be passed using pass-by-value, pass-by-reference, and pass-by-address. In pass-by-value we pass the copy of an object to a function. In pass-by-reference we pass a reference to the existing object. In pass-by-address we pass the address of an existing object. Following program demonstrates all three methods of passing objects as function arguments:



Returning Objects


We can not only pass objects as function arguments but can also return objects from functions. We can return an object in the following three ways:

  1. Returning by value which makes a duplicate copy of the local object.
  2. Returning by using a reference to the object. In this way the address of the object is passed implicitly to the calling function.
  3. Returning by using the ‘this pointer’ which explicitly sends the address of the object to the calling function.


Following program demonstrates the three ways of returning objects from a function:



this Pointer


For every object in C++, there is an implicit pointer called this pointer. It is a constant pointer which always points to the current object. Uses of this pointer are as follows:

  • When data member names and function argument names are same, this pointer can be used to distinguish a data member by writing this->member-name.
  • It can be used inside a member function to return the current object by address by writing return *this.


The this pointer cannot be used along with static functions as static functions are not part of any object. Following program demonstrates the use of this pointer:



Modify the area() function in the above program with the following code:



Now again compile and execute the program. Observe the value of radius in the output. Is it correct?


Constant Parameters and Members


Constant Member Functions


Member functions in a class can be declared as constant if that member function has no necessity of modifying any data members. A member function can be declared as constant as follows:



Following program demonstrates the use of constant member functions:



In the above program there is no need for area() and peri() functions to modify the data member r. So, they are declared as constant member functions.


Constant Parameters


To prevent functions from performing unintended operations on data members of an object, we can declare the object arguments as constant arguments as follows:


const ClassName object-name


Following program demonstrates the use of constant parameters:



In the above program inside the get_radius() function, Circle object has been declared as constant. So performing c.r = 30 is invalid as modifying constant values is illegal.


Pointers within a Class


Pointers can be used inside a class for the following reasons:

  • Pointers save memory consumed by objects of a class.
  • Pointers can be used to allocate memory dynamically i.e., at run time.


Following program demonstrates the use of pointers within a class:



In the above program marks is a pointer inside the class Student. It is used to allocate memory dynamically inside the get_marks() function with the help of new  operator.


Local Classes


A class which is declared inside a function is called a local class. A local class is accessible only within the function it is declared. Following guidelines should be followed while using local classes:

  • Local classes can access global variables only along with scope resolution operator.
  • Local classes can access static variables declared inside a function.
  • Local classes cannot access auto variables declared inside a function.
  • Local classes cannot have static variables.
  • Member functions must be defined inside the class.
  • Private members of the class cannot be accessed by the enclosing function if it is not declared as a friend function.


Below example demonstrates a local class:



Nested Classes


C++ allows programmers to declare one class inside another class. Such classes are called nested classes. When a class B is declared inside class A, class B cannot access the members of class A. But class A can access the members of class B through an object of class B. Following are the properties of a nested class:

  • A nested class is declared inside another class.
  • The scope of inner class is restricted by the outer class.
  • While declaring an object of inner class, the name of the inner class must be preceded by the outer class name and scope resolution operator.


Following program demonstrates the use of nested classes:



Object Composition


In real-world programs an object is made up of several parts. For example a car is made up of several parts (objects) like engine, wheel, door etc. This kind of whole part relationship is known as composition which is also known as has-a relationship. Composition allows us to create separate class for each task. Following are the advantages or benefits of composition:

  • Each class can be simple and straightforward.
  • A class can focus on performing one specific task.
  • Classes will be easier to write, debug, understand, and usable by other people.
  • Lowers the overall complexity of the whole object.
  • The complex class can delegate the control to smaller classes when needed.


Following program demonstrates composition:



Friend Functions


A friend function is a non-member function which can access the private and protected members of a class. To declare an external function as a friend of the class, the function prototype preceded with friend keyword should be included in that class. Syntax for creating a friend function is as follows:



Following are the properties of a friend function:

  • Friend function is a normal external function which is given special access to the private and protected members of a class.
  • Friend functions cannot be called using the dot operator or -> operator.
  • Friend function cannot be considered as a member function.
  • A function can be declared as friend in any number of classes.
  • As friend functions are non-member functions, we cannot use this pointer with them.
  • The keyword friend is used only in the declaration. Not in the definition.
  • Friend function can access the members of a class using an object of that class.


Following program demonstrates using a friend function:



In the above program show_details() function was able to access the private data member name as it is a friend of Student class.


Friend Class


A friend class is a class which can access the private and protected members of another class. If a class B has to be declared as a friend of class A, it is done as follows:



Following are properties of a friend class:

  • A class can be friend of any number of classes.
  • When a class A becomes the friend of class B, class A can access all the members of class B. But class B can access only the public members of class A.
  • Friendship is not transitive. That means a friend of friend is not a friend unless specified explicitly.


Following program demonstrates a friend class:



In the above program class B has been declared as a friend of class A. That is why it is able to access private member x of class A.


Bit Fields in Classes


A field or member inside a class which allows programmers to save memory are known as bit fields. As we know a integer variable occupies 32 bits (on a 32-bit machine). If we only want to store two values like 0 and 1, only one bit is sufficient. Remaining 31-bits are wasted. In order to reduce such wastage of memory, we can use bit fields. Syntax of a bit field is as follows:


type-specifier declarator: width;


In the above syntax declarator is an identifier (bit-field name), type-specifier is the data type of the declarator and width is the size of bit field.


Following are the properties of bit-fields:

  • C++ does not allow arrays of bit fields, pointers to bit fields, and functions returning bit fields.
  • The declarator is optional and is used only to name the bit field.
  • The address operator (&) cannot be used with bit fields.
  • When a value that is out of range is assigned to a bit field, the lower-order bit pattern is preserved.
  • Bit fields with a size of 0 must be unnamed.


Following program demonstrates bit field in a class:



In the above program size of status field is only 1-bit. It can store either a 0 or 1.


Volatile Objects and Member Functions


An object which can be modified by some unknown forces (like hardware) other than the program itself can be declared as volatile. Compiler doesn’t apply any optimizations for such volatile objects. Syntax for declaring an volatile object is as follows:


volatile ClassName object-name;


A member function can be declared as volatile to make the access to member variables to be volatile. A volatile object can access only volatile functions. Syntax for creating a volatile function is as follows:


return-type function-name(params-list) volatile;


Following program demonstrates both volatile objects and volatile programs:



In the above program volatile function is ­get_name() and volatile object is s2. The object s2 can access only volatile member functions.

Related Links:

Scroll Up