Classes and Objects
Classes
• A class is defined in C++ using the keyword class
followed by the name of the class.
• The body of the class is defined inside curly brackets
and terminated by a semicolon at the end.
Syntax:
class ClassName {
// some data
// some functions
};
Example
class Room {
public:
double length;
double breadth;
double height;
double calculate_area(){
return length * breadth;
}
double calculate_volume(){
return length * breadth * height;
}
A Class
• Here, we defined a class named Room.
• The variables length, breadth, and height declared
inside the class are known as data members.
• And the functions calculate_area() and
calculate_volume () are known as class member
functions.
C++ Objects
• When a class is defined, only the specification for the
object is defined; no memory or storage is allocated.
• To use the data and access functions defined in the
class, we need to create objects.
Syntax
ClassName object_name;
• We can create objects of Room class (defined in the
above example) as follows
// sample function
void sample_function() {
// create objects
Room room1, room2;
}
int main(){
// create objects
Room room3, room4;
}
• Here, two objects room1 and room2 of the Room class
are created in sample_function().
• Similarly, the objects room3 and room4 are created in
main().
• As we can see, we can create objects of a class in any
program function.
• We can also create objects of a class within the class
itself or in other classes.
• Also, we can create as many objects as we want from a
single class.
Access Data Members and
Member Functions
• We can access the data members and member
functions of a class by using a . (dot) operator.
For example
room2.calculate_area();
• This will call the calculate_area() function inside the
Room class for object room2.
• Similarly, the data members can be accessed as:
room1.length = 5.5;
• In this case, it initializes the length variable of room1 to
5.5.
Example
• Write a C++ program that will calculate the area and
volume of a room. Use the Room as a class and room1 as
its object
• Program
• In this program, we have used the Room class and its
object room1 to calculate the area and volume of a
room.
• In main(), we assigned the values of length, breadth,
and height with the code:
room1.length = 42.5;
room1.breadth = 30.8;
room1.height = 19.2;
• We then called the functions calculate_area() and
calculate_volume() to perform the necessary
calculations.
Note
• The use of the keyword public in the program.
• This means the members are public and can be
accessed anywhere from the program, also we
have a keyword private(not used) which means that the
members are private and can be accessed only
within a class member.
Example 2
• This code below defines a Book class with two
properties (title and author) and a method (read).
• An object myBook is created from the Book class, and
its title property is set.
• When myBook.read() is called, it outputs “Reading
Simplifies OOP Using C++”.
• A program