0% found this document useful (0 votes)
21 views33 pages

C++ Class Pointers and Const Functions

Uploaded by

karim
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)
21 views33 pages

C++ Class Pointers and Const Functions

Uploaded by

karim
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/ 33

Programming Techniques

Eng. Ahmad Salama


[ 0100 14 13 225 ]

[ Spring 2024 ]

[ CMPS102 ]

C++ Classes
Part [2]
[5]
1
C++ Classes by Eng. Ahmad Salama [ 0100 14 13 225 ]
Pointers to class objects
A pointer to a class object in C++ is a variable that holds the
memory address of the object. It allows indirect access to the
object, providing a way to manipulate and interact with the object
dynamically. Pointers to objects are particularly useful when dealing
with dynamically allocated memory, enabling flexible memory
management and dynamic object creation.

In C++, when an object is created, it occupies a specific memory


location. Pointers to objects store the address of the object in
memory. By using pointers, programmers can access and modify the
object indirectly through the pointer.

When using a pointer to an object, accessing data members or


member functions of an object can be done using the -> operator
( This is called the arrow operator or the member access operator )

2
C++ Classes by Eng. Ahmad Salama [ 0100 14 13 225 ]
Ex:
#include <iostream>
using namespace std;
class Test
{
public:
int n = 5; // define a data member

void display () // define a member function


{ cout << " In display() function n = "<<n<<endl; }

};
int main ()
{
Test T;
Test *ptr; // declare a pointer to a class object
ptr = &T; // store the address of the object in ptr

cout << " In main() function n = " << T.n << endl;
T.display();

// accessing the data member and the member function through


// pointer ptr

cout << " In main() function n = " << ptr->n << endl;
ptr->display();
return 0;
}
-> is called the arrow operator or the member access operator

3
C++ Classes by Eng. Ahmad Salama [ 0100 14 13 225 ]
Output
In main() function n = 5
In display() function n = 5
In main() function n = 5
In display() function n = 5

4
C++ Classes by Eng. Ahmad Salama [ 0100 14 13 225 ]
Dynamic allocation of class objects
In C++, the objects can be created at run-time.
C++ supports two operators new and delete to perform memory
allocation and de-allocation.
These types of objects are called dynamic objects.
The new operator is used to create objects dynamically and the
delete operator is used to delete objects dynamically.
The dynamic objects can be created with the help of pointers.
Ex:
// C++ program to implement dynamic objects
#include<iostream>
using namespace std;

// Class definition
class Test
{
// Data members
int a, b;
public:

// Constructor to initialize data members of class


Test()
{
cout << "Constructor is called" << endl;
a = 1;
b = 2;
};

5
C++ Classes by Eng. Ahmad Salama [ 0100 14 13 225 ]
// Destructor
~Test()
{
cout << "Destructor is called" << endl;
}

// Function to print values of data members


void show()
{
cout << "a = " << a << endl;
cout << "b = " << b << endl;
}
};
// Driver code
int main()
{
// pointer to class object
Test *ptr;

// dynamic object creation


ptr = new Test;

// Accessing member function through pointer to object using arrow


// operator
ptr->show();

// Destroying dynamic object


delete ptr;
return 0; }

6
C++ Classes by Eng. Ahmad Salama [ 0100 14 13 225 ]
Output
Constructor is called
a = 1
b = 2
Destructor is called

7
C++ Classes by Eng. Ahmad Salama [ 0100 14 13 225 ]
const objects and const member functions

const variables:
Ex 1:
int main()
{
const int num = 1;
num = 5; // Error! Modifying the value of a constant
return 0;
}

Ex 2:
int main()
{
const int num = 5;
int X[num];
// num is const so can be used for the size of automatic arrays
return 0;
}

The keyword const may be used to:


1. Specify a const object of a class
2. Specify const member functions of a class

8
C++ Classes by Eng. Ahmad Salama [ 0100 14 13 225 ]
const objects:
An object when declared as const cannot be modified and hence,
can invoke only const member functions as these functions ensure
not to modify the object. A const object can be created by
prefixing the const keyword to the object declaration. Any attempt
to change the data member of const objects results in a compile-
time error.

Ex 1:
#include <iostream>
using namespace std;
class Test
{
public:

int a; // define data member

Test () // create constructor of the class Test


{ a = 10; } // define a value to a

};
int main ()
{
const Test Obj; // declare a constant object
cout << " The value of a is: " << Obj.a << endl;
// Obj.a = 20; // This gives a compile time error
return 0;
} Output
The value of a is: 10

9
C++ Classes by Eng. Ahmad Salama [ 0100 14 13 225 ]
const member functions:
Constant member functions are those functions that are denied
permission to change the values of the data members of their class.
To make a member function constant, the keyword const is
appended to the function prototype and also to the function
definition header.

10
C++ Classes by Eng. Ahmad Salama [ 0100 14 13 225 ]
Ex 1:
The below C++ program demonstrates that data members can be
updated in a member function that is not constant.

#include <iostream>
using namespace std;
class Demo
{
int x;
public:
void set_data(int a)
{ x = a; }

int get_data()
{
++x;
return x;
}
};

main()
{
Demo d;
d.set_data(10);
Output
cout <<d.get_data()<< endl;
11

return 0;
}

11
C++ Classes by Eng. Ahmad Salama [ 0100 14 13 225 ]
Ex 2:
The below C++ program demonstrates that data members cannot be
updated in a const member function.

#include <iostream>
using namespace std;
class Demo
{
int x;
public:
void set_data(int a)
{ x = a; }

// constant member function


int get_data() const
{
++x; // Error while attempting to modify the data member x
return x;
}
};

main()
{
Demo d;
d.set_data(10);
cout <<d.get_data()<< endl;

return 0;
}

12
C++ Classes by Eng. Ahmad Salama [ 0100 14 13 225 ]
Ex 3:
The below C++ code demonstrates how to define constant member
functions outside the class definition.

// Constant member function defined outside the class


#include <iostream>
using namespace std;

class Demo
{
int x;

public:
// non const member function
void set_data(int);

// const member function


int get_data() const;
};

// non const function definition for setting the value of x.


void Demo::set_data(int a)
{ x = a; }

// const function definition for retrieving the value of x


// ( const member function ).
int Demo::get_data() const
{ return x; }

13
C++ Classes by Eng. Ahmad Salama [ 0100 14 13 225 ]
int main()
{
Demo d;
// Set the value of x to 10 using the non-const member function.
d.set_data(10);
// Print the value of x using the const member function.
cout << d.get_data();

return 0;
}

Output
10

14
C++ Classes by Eng. Ahmad Salama [ 0100 14 13 225 ]
When a function is declared as const, it can be called by any type
of object ( const or non const ).
Ex 4:
The below C++ program demonstrates that const member functions
can be called by non-const objects.

#include <iostream>
using namespace std;

class Test
{
int x;

public:
Test( int a = 0 )
{ x = a; } // Constructor

// const member function


int getValue() const { return x; }
};
int main()
{
Test T(20); // non const object
cout << T.getValue();
return 0;
}

Output
20

15
C++ Classes by Eng. Ahmad Salama [ 0100 14 13 225 ]
Ex 5:
The below C++ program demonstrates that const member functions
can be called by const objects.

#include <iostream>
using namespace std;

class Test
{
int x;

public:
Test( int a = 0 ) // Constructor
{ x = a; }

// const member function


int getValue() const { return x; }
};

int main()
{
const Test T(20); // const object
cout << T.getValue();
return 0;
}

Output
20

16
C++ Classes by Eng. Ahmad Salama [ 0100 14 13 225 ]
Non-const functions can only be called by non-const objects.
Ex 6:
The following C++ program that demonstrate that non-const member
functions cannot be called by const objects
( it will give a compile-time Error )

#include <iostream>
using namespace std;

class Test
{
int x;

public:
Test(int a = 0) { x = a; } // Constructor

// non const member function


int getValue() { return x; }
};

int main()
{

const Test T(20); // const object


cout << T.getValue(); // Compile-time Error
return 0;
}

17
C++ Classes by Eng. Ahmad Salama [ 0100 14 13 225 ]
Why are const member functions used in C++?
We use const member functions in C++ to avoid accidental object
changes. It is highly recommended to make as many functions const
as possible so that the chances of errors in the program are
minimal.

Const Member Function Use Cases:


The two use cases of the const member functions are as follows:

1. A const member function is called by any type of object, i.e.,


either by a const or a non-const object.

2. A non-const function can only be called by a non-const object.

18
C++ Classes by Eng. Ahmad Salama [ 0100 14 13 225 ]
Ex 7:
#include <iostream>
using namespace std;
class Test
{
int x;
public:
Test() // constructor
{
x=0;
}
void set_value( int a )
{
x=a;
}
int get_square()
{
return x*x;
}
int get_value() const
{
return x;
}

};

19
C++ Classes by Eng. Ahmad Salama [ 0100 14 13 225 ]
int main()
{
Test obj1;
const Test obj2;

obj1.set_value(2);

obj2.set_value(3);
// gives an error as obj2 is a const obj and the value of its data
// member is set by a default constructor and cannot be changed

cout<<obj1.get_square()<<endl;
// non-const object calling non const function

cout<<obj2.get_value()<<endl;
// const function is called by a const object

cout<<obj1.get_value()<<endl;
// const function is called by a non-const object

cout<<obj2.get_square()<<endl;
// gives an error as a const object cannot call a non-const function

20
C++ Classes by Eng. Ahmad Salama [ 0100 14 13 225 ]
Constant Data Members of a class
Constant Data members are like the variables that are declared
inside a class, but once the data member is initialized, it never
changes, not even in the constructor or destructor.
A constant data member is declared using the const keyword before
the data type inside the class.
The const data members cannot be assigned values during their
declaration, however, they are assigned their values through
constructors.

Ex 1:

#include <iostream>
using namespace std;
class Test
{

public:

const int x; // const data member

// create a constructor and assign the const data member its value
Test ( int y ) : x(y)
{
cout << " The value of y is: " << y << endl;
}

21
C++ Classes by Eng. Ahmad Salama [ 0100 14 13 225 ]
int get_value()
{
// x++; // not allowed as the data member is a const data member
return x;
}

};

int main ()
{

Test T(10);
cout << "The value of constant data member x is: " <<T.x<< endl;

cout << "The value of constant data member x is: "


<<T.get_value()<< endl;

// T.x = 5; // This gives a compile time error.

return 0;
}

Output
The value of y is: 10
The value of constant data member x is: 10
The value of constant data member x is: 10

22
C++ Classes by Eng. Ahmad Salama [ 0100 14 13 225 ]
Ex 2:
#include <iostream>
using namespace std;
class Circle
{
public:
// Constructor with initialization list to initialize const and non const
// data members
Circle(double r) : PI(3.14159) , radius(r) {}

// const member function to calculate area


double calculateArea() const
{ return PI * radius * radius; }

private:
const double PI; // const data member ( PI )
double radius; // Non-const data member ( radius )
};

int main()
{
Circle C(10.0);
cout << "Area of the circle is: " << C.calculateArea() << endl;
// C.PI = 3.14; // Compile time Error!
return 0;
}

Output
Area of the circle is: 314.159

23
C++ Classes by Eng. Ahmad Salama [ 0100 14 13 225 ]
Complex Objects and Composition
An object is the basic unit of Object-Oriented Programming and
represents the real-life entities.

Complex objects are the objects that are built from smaller or a
collection of objects. For example, a mobile phone is made up of
various objects like a camera, battery, screen, sensors.

In object-oriented programming languages, object composition is


used for objects that have a “has-a” relationship with each other.
For example, a mobile has-a battery, has-a sensor, has-a screen,
etc. Therefore, the complex object is called the whole or the
owning object whereas a simpler object is often referred to as the
part or the owned object. In this case, all the objects or
components are the part objects which together make up the
complex ( whole ) object (mobile).

24
C++ Classes by Eng. Ahmad Salama [ 0100 14 13 225 ]
Ex 1:
// C++ program to implement a composition
#include <iostream>
using namespace std;

// First Class which is the parent class


class One
{

private:
int num; // Private data member

// Public set and get member functions


public:
void set(int i)
{
num = i;
}
int get()
{
return num;
}
};

25
C++ Classes by Eng. Ahmad Salama [ 0100 14 13 225 ]
// Another class which is the child class
class Two
{

public:
One O; // Public Object of the previous class
void show() // Public member function
{
cout << "Number = "<< O.get() <<endl;
}
};

int main()
{
// Creating an object of class Two
Two T;

// Perform some operation using the object of One in this class


T.O.set(100);

T.show();
}

Output
Number = 100

26
C++ Classes by Eng. Ahmad Salama [ 0100 14 13 225 ]
The concept of complex objects is being used in most of the real-
world scenarios.
The advantages of using this concept are:

1. Each individual class can be simple and straightforward.

2. One class can focus on performing one specific task and obtain
one behavior.

3. The class is easier to write, debug, understand, and usable by


other programmers.

4. While simpler classes can perform all the operations, the


complex class can be designed to coordinate the data flow between
the simpler classes.

5. It lowers the overall complexity of the complex object because


the main task of the complex object would then be to delegate
tasks to the sub-objects, who already know how to do them.

6. The most important advantage is if any changes have to be made


in a part class, only the part class can be changed rather than
changing the entire whole class.
For example, if we want to change the battery class in the mobile
object, with the help of composition, the changes are only made in
the battery class and the entire mobile object works fine with the
updated changes.

27
C++ Classes by Eng. Ahmad Salama [ 0100 14 13 225 ]
Composition vs Aggregation vs Association
In object-oriented programming, particularly in C++, the terms
"Composition," "Aggregation," and "Association" refer to different
kinds of relationships between classes. These relationships describe
how one class is related to another and how they interact.

Let's define each term:

1) Composition:
Composition is a strong form of association.
Composition represents a "has-a" relationship where one class ( the
whole ) owns another class ( the part ) and is responsible for its
creation and destruction.
The lifetime of the owned ( part ) object is dependent on the
lifetime of the owning ( whole ) object, i.e. the owned ( part )
object cannot exist independently of the owning ( whole ) object.
A composition relationship is represented in C++ as an object of one
class being contained within another class. The contained ( owned )
object is said to be a part of the containing ( owning ) object, and
it cannot exist independently of the containing object. If the
containing object is destroyed, the contained object is automatically
destroyed along with it.

28
C++ Classes by Eng. Ahmad Salama [ 0100 14 13 225 ]
For example, consider a class Car and a class Engine.
If a car "has an" engine, we can say that there is a composition
relationship between the two classes, because a Car owns its
Engine, and an Engine cannot exist without a Car.
We can implement this composition relationship in C++ as follows:
Ex:
class Engine // owned or contained class
{
// Engine class definition
};
class Car // owning or containing class
{
private:
Engine E; // Composition relationship
};
int main()
{
Car C;
}
In this example, an object E of class Engine is contained within an
object C of class Car, representing the composition relationship
between the two classes. The contained object E cannot exist
independently of the containing object C, and if the Car object C is
destroyed, the Engine object E is automatically destroyed along
with it.

29
C++ Classes by Eng. Ahmad Salama [ 0100 14 13 225 ]
2) Aggregation:
Aggregation is a weaker form of association. It also represents a
"has-a" relationship, but in this case, the lifetime of the owned
( contained ) object is not dependent on the owning ( containing )
object,
i.e. the owned object can exist independently of the owning object.
In C++, this is often implemented by having a member variable of a
class that is a pointer or reference to the other class.
The contained objects are said to be part of the containing object,
but they can exist independently of the containing object. If the
containing object is destroyed, the contained objects are not
automatically destroyed along with it.
For example, a Department class might have an aggregation
relationship with Employee class, because a Department has
Employees, but Employees can exist outside of the Department.

30
C++ Classes by Eng. Ahmad Salama [ 0100 14 13 225 ]
Ex:
class Employee
{
// Employee class definition
};

class Department
{
private:
Employee* employees[5]; // Aggregation relationship
};
int main()
{
Department D;
}

In this example, an instance of the Department class contains


pointers to objects of the Employee class, representing the
aggregation relationship between the two classes. The contained
objects employees can exist independently of the containing
object Department, and if the Department object is destroyed,
the Employee objects are not automatically destroyed along with it.

31
C++ Classes by Eng. Ahmad Salama [ 0100 14 13 225 ]
3) Association
Association is a very general relationship between classes. It
signifies that objects of one class are connected to objects of
another class.
Unlike composition and aggregation, association doesn't imply
ownership or dependency.
It could be a simple relationship where objects of one class use
objects of another class, or it could be a more complex
relationship.
In C++, association can be represented by member variables,
function parameters, return types, etc., that reference instances
of another class.
For example, a Teacher class might have an association with a
Student class, because teachers interact with students, i.e. A
teacher can teach to one student or more and a student can learn
from one teacher or more.
Ex:
class Student
{
// Student class definition
};
class Teacher
{ public:
void AssignGrade(Student* S, int grade); // Association relationship
};

32
C++ Classes by Eng. Ahmad Salama [ 0100 14 13 225 ]
In summary:

Composition Aggregation Association


Composition implies Aggregation Association
strong ownership represents a weaker represents a
where the lifetime of form of ownership relationship between
owned objects is tied where the classes without
to the lifetime of aggregated ( owned ) implying ownership.
the owning object. objects can exist
independently.

33
C++ Classes by Eng. Ahmad Salama [ 0100 14 13 225 ]

You might also like