You are on page 1of 28

EC-204 Data Structures and Object

Oriented Programming

Classes

Dr Tahir Nawaz
www.tahirnawaz.com
tahir.nawaz@ceme.nust.edu.pk
Introduction
• Like structures, classes are also user defined types that
specify how objects of its type can be created and used

• As in other modern languages, in C++, a class is a key


building block for object oriented programming

• A class can have different data types as well as


functions as it’s members

• When we define a class, a blueprint for a data type is


defined. This doesn't actually define any data, but it does
define what the class name means, that is, what an
object of the class will consist of and what operations
can be performed on such an object.
Defining a C++ 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. The syntax
is as follows:

class class_name {
access_specifier_1:
member1;
access_specifier_2:
member2;
...
} object_names;
Defining a C++ class (contd.)
• Where class_name is a valid identifier for the class,
object_names is an optional list of names for objects of
this class. The body of the declaration can contain
members, which can either be data or function
declarations, and optionally access specifiers.
• An access specifier is one of the following three
keywords: private, public or protected. These
specifiers modify the access rights for the members that
follow them:
• private members of a class are accessible only from within
other members of the same class
• protected members are accessible from other members of the
same class, but also from members of their derived classes.
• Finally, public members are accessible from anywhere where
the object is visible.
Defining a C++ class (contd.)
• By default, all members of a class declared with the
class keyword have private access for all its members.
Therefore, any member that is declared before any other
access specifier has private access automatically.
class Rectangle {
int width, height;
public:
void set_values (int,int);
int area (void); };
• The above definition is the same as follows:
class Rectangle {
private:
int width, height;
public:
void set_values (int,int);
int area (void);};
Defining C++ objects
• A class provides the blueprints for objects, so basically
an object is created from a class. We declare objects of
a class with exactly the same sort of declaration that we
declare variables of basic types. For example, the
following statements declare two objects of class
Rectangle:

Rectangle rect1;
Rectangle rect2;

• Both of the objects rect1 and rect2 will have their own
copy of data members.
Classes vs. Structures
• Class members are private by default, whereas a
struct is a class where members are public by default:

struct X {
int m;
// … };

• Means

class X {
public:
int m;
// … };
Classes vs. Structures
• So, unlike structures, we can use access specifiers with
classes, meaning a structure is not safe in the sense it
could not hide its implementation details from the end-
user, whereas a class is secure as it may hide its
programming and design details.

• There is no concept defining constructors and


destructors in structures, whereas classes enable us to
define and use them (we’ll see them in a bit what they
are are and why they are useful!)
Accessing data members
• The public data members of objects of a class can be
accessed using the direct member access operator (.).
Try the following example:
#include <iostream>
using namespace std;

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 box here
Accessing data members
// 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; }
Class member functions
• A member function is a function that has its definition or
its prototype within the class definition like any other
variable. It operates on any object of the class of which it
is a member, and has access to all the members of a
class for that object.

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
};
Class member functions (contd.)
• Member functions can be defined within class definition
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;
}
};
• Or separately using scope operator (::, two colons)
double Box::getVolume(void) {
return length * breadth * height;
}
Class member functions (contd.)
• Let us put above concepts to set and get the value of
different class members in a class
#include <iostream>

using namespace std;

class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box

// Member functions declaration


double getVolume(void);
void setLength( double len );
void setBreadth( double bre );
void setHeight( double hei );
};
Class member functions (contd.)
// Member functions definitions
double Box::getVolume(void) {
return length * breadth * height;
}

void Box::setLength( double len ) {


length = len;
}
void Box::setBreadth( double bre ) {
breadth = bre;
}
void Box::setHeight( double hei ) {
height = hei;
}

// Main function for the program


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
Class member functions (contd.)
// 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();
cout << "Volume of Box1 : " << volume <<endl;

// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
The Class Constructor
• A class constructor is a special member function of a
class that is executed whenever we create new objects
of that class.

• 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.

• 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
The Class Constructor (contd.)
• Example:
#include <iostream>

using namespace std;


class Line {
public:
void setLength( double len );
double getLength( void );
Line(double len); // This is the
constructor

private:
double length;
};
The Class Constructor (contd.)
// Member functions definitions including
constructor
Line::Line( double len) {
cout << "Object is being created, length = " <<
len << endl;
length = len;
}
void Line::setLength( double len ) {
length = len;
}
double Line::getLength( void ) {
return length;
}
The Class Constructor (contd.)

// Main function for the program


int main() {
Line line(10.0);

// get initially set length.


cout << "Length of line : " << line.getLength()
<<endl;

// set line length again


line.setLength(6.0);
cout << "Length of line : " << line.getLength()
<<endl;

return 0;
}
The Class Destructor
• A destructor is a special member function of a class
that is executed whenever an object of it's class goes out
of scope or whenever the delete expression is applied to
a pointer to the object of that class.

• 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 releasing resources before coming out of the
program like closing files, releasing memories etc.
The Class Destructor (contd.)
• Example:

class Box {
public:
Box() {
cout<<“Box-type object is created” << endl;
}
~Box() {
cout<<“Box-type object is deleted” << endl;
}
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
double getVolume(void);// Returns box volume
};
Overloading Constructor
• Like any other function, a constructor can also be
overloaded with different versions taking different
parameters: with a different number of parameters
and/or parameters of different types.
• The compiler will automatically call the one whose
parameters match the arguments
• The constructor that takes no parameters is called
default constructor, and it is special because it is called
when an object is declared but is not initialized with any
arguments.
Rectangle rectb; // ok, default constructor
called
Rectangle rectc(); // oops, default constructor
NOT called
Overloading Constructor
• Example:
// overloading class constructors
#include <iostream>
using namespace std;

class Rectangle {
int width, height;
public:
Rectangle ();
Rectangle (int,int);
int area (void) {return
(width*height);}
};
Overloading Constructor (contd.)
Rectangle::Rectangle () {
width = 5;
height = 5;
}
Rectangle::Rectangle (int a, int b) {
width = a;
height = b;
}

int main () {
Rectangle rect (3,4);
Rectangle rectb;
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0;
}
Pointer to a Class
• A pointer to a C++ class is done exactly the same way
as a pointer to a structure and to access members of a
pointer to a class we use the member access operator
(->), just as you do with pointers to structures. Also as
with all pointers, you must initialize the pointer before
using it.
Box Box1;
Box *class_pointer;

• Now, we can store the address of a Box-type class


object in the above declared pointer variable.
• We can therefore initialize a pointer to class as follows:

class_pointer = &Box1;
Pointer to a Class (contd.)
• Example:
#include <iostream>
using namespace std;

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
};
Pointer to a Class (contd.)
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.

// Save the address of first object


ptrBox = &Box1;

// Now try to access a member using member access operator


cout << "Volume of Box1: " << ptrBox->Volume() << endl;

// Save the address of second object


ptrBox = &Box2;

// Now try to access a member using member access operator


cout << "Volume of Box2: " << ptrBox->Volume() << endl;

return 0;
}
Acknowledgements/References
• https://www.tutorialspoint.com/cplusplus/index.htm

• https://www.cplusplus.com/

• Deital and Deital, “C++ How to Program”, Latest Edition

• Stroustrup, “Programming – Principles and Practice


Using C++”, Latest Edition

You might also like