6 C++ Classes and Objects - Handout 6 PDF
6 C++ Classes and Objects - Handout 6 PDF
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard,
bike etc. It can be physical and logical. It is a basic unit of Object-Oriented Programming and represents
the real-life entities. A C++ program creates many objects which interact by invoking methods.
An Object is physical entity and in C++, it has three characteristics:
• State
• Behavior
• Identity
Example
Employee e;
State: Represents data (value) of an object.
Behavior: Represents the behavior (functionality) of an object such as deposit, withdraw etc.
Identity: Object identity is typically implemented via a unique ID. The value of the ID is not visible to the
external user. But it is used internally by the JVM to identify each object uniquely.
Class
Collection of objects is called class. It is a logical entity. A class is a group of objects that has common
properties. A class is a user-defined blueprint or prototype from which objects are created. It represents
the set of properties or methods that are common to all objects of one type.
A class in C++ contains the following properties;
• Data Member
• Method
• Constructor
• Block
• Class and Interface
Look at the following illustration to see the difference between class and objects:
Class: Fruit, objects: Apple, Banana, and Mango
Page 1 of 15
C++ Programming Handout 6
Another example:
Class: Car, objects: Volvo, Audi, Toyota
So, a class is a template for objects, and an object is an instance of a class.
When the individual objects are created, they inherit all the variables and functions from the class.
The car has data members, such as weight and color, and methods, such as drive and brake.
Data members and methods are basically variables and functions that belong to the class. These are often
referred to as "class members".
Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism. The process of
obtaining the data members and methods from one class to another class is known as inheritance. It is one
of the fundamental features of object-oriented programming.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example: to convince
the customer differently, to draw something e.g. shape or rectangle etc. In C++, we use Function
overloading and Function overriding to achieve polymorphism. Here one form represent original form or
original method always resides in base class and multiple forms represents overridden method which
resides in derived classes.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example: phone call, we
don't know the internal processing. In C++, we use abstract class and interface to achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation. For
example: capsule, it is wrapped with different medicines. The main advantage of using of encapsulation is
to secure the data from other methods, when we make a data private then this data only used within that
class, but this data is not accessible outside the class.
Advantage of OOPs over Procedure-oriented programming language
1. OOPs makes development and maintenance easier where as in Procedure-oriented programming
language (e.g. Fortran, Pascal) it is not easy to manage if code grows as project size grows.
2. OOPs provide data hiding whereas in Procedure-oriented programming language a global data can
be accessed from anywhere.
3. OOPs provide ability to simulate real-world event much more effectively. We can provide the
solution of real word problem if we are using the Object-Oriented Programming language.
Page 2 of 15
C++ Programming Handout 6
• The public keyword is an access specifier, which specifies that members (attributes
and methods) of the class are accessible from outside the class. You will learn more
about access specifiers later.
• Inside the class, there is an integer variable myNum and a string variable myString. When
variables are declared within a class, they are called attributes.
• At last, end the class definition with a semicolon ;
Create an Object
In C++, an object is created from a class. We have already created the class named MyClass, so now we
can use this to create objects.
To create an object of MyClass, specify the class name, followed by the object name.
To access the class attributes (myNum and myString), use the dot syntax (.) on the object:
Example
Create an object called "myObj" and access the attributes:
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
int main() {
MyClass myObj; // Create an object of MyClass
Page 3 of 15
C++ Programming Handout 6
string model;
int year;
};
int main() {
// Create an object of Car
Car carObj1;
carObj1.brand = "BMW";
carObj1.model = "X5";
carObj1.year = 1999;
Class Methods
Methods are functions that belong to the class.
There are two ways to define functions that belong to a class:
• Inside class definition
• Outside class definition
In the following example, we define a function inside the class, and we name it "myMethod".
Note: You access methods just like you access attributes; by creating an object of the class and using the
dot syntax (.):
Inside Example
class MyClass { // The class
public: // Access specifier
void myMethod() { // Method/function defined inside the class
cout << "Hello World!";
}
};
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
To define a function outside the class definition, you have to declare it inside the class and then define it
outside of the class. This is done by specifying the name of the class, followed the scope resolution ::
operator, followed by the name of the function:
Outside Example
class MyClass { // The class
public: // Access specifier
void myMethod(); // Method/function declaration
};
Page 4 of 15
C++ Programming Handout 6
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
Parameters
You can also add parameters:
Example
#include <iostream>
using namespace std;
class Car {
public:
int speed(int maxSpeed);
};
int main() {
Car myObj; // Create an object of Car
cout << myObj.speed(200); // Call the method with an argument
return 0;
}
The keywords public, private, and protected are called access specifiers. A class can have multiple public,
protected, or private labeled sections.
Page 5 of 15
C++ Programming Handout 6
Note: By default, all members and function of a class is private i.e if no access specifier is specified.
Syntax of Declaring Access Specifiers in C++
Syntax
class
{
private:
// private members and function
public:
// public members and function
protected:
// protected members and function
};
Public Access Specifier in C++
Public class members are accessible outside the class and it is available for every one.
Syntax
class Public_Access_Specifier
{
public: // public access specifier
int a; // Data Member Declaration
void display(); // Member Function declaration
}
Private Access Specifier in C++
Private class members are accessible within the class and it is not accessible outside the class. If someone
try to access outside the it gives compile time error. By default class variables and member functions are
private.
Syntax
class Private_Access_Specifier
{
private: // private access specifier
int a; // Data Member Declaration
void display(); // Member Function declaration
}
Private and Public Access Specifier Example in C++
Example
#include<iostream>
using namespace std;
class A
{
private:
int a;
public:
int b;
public:
void show()
{
a=10 ;
b=20;
clrscr();
//Every members can be access here, same class
cout<<"\nAccessing variable within the class"<<endl;
Page 6 of 15
C++ Programming Handout 6
cout<<"Value of a: "<<a<<endl;
cout<<"Value of b: "<<b<<endl;
}
};
void main()
{
A obj; // create object
obj.show();
getch();
}
Note: If we access variable a inside main method it will give compile time error
Output
Accessing variable within the class
value of a: 10
value of b: 20
value of c: 30
class Declaration
{
private:
int a;
public:
int b;
protected:
int c;
public:
void show()
{
a=10;
Page 7 of 15
C++ Programming Handout 6
b=20;
c=30;
cout<<"Value of a: "<<a<<endl;
cout<<"Value of b: "<<b<<endl;
cout<<"Value of c: "<<c<<endl;
}
};
void main()
{
clrscr();
Declaration d; // create object
d.show();
Page 8 of 15
C++ Programming Handout 6
Accessing variable outside the class
Value of b: 20
#include <iostream>
using namespace std;
class Geeks
{
// Access specifier
public:
// Data Members
string geekname;
// Member Functions()
void printname()
{
cout << "Geekname is: " << geekname;
}
};
int main() {
#include <iostream>
using namespace std;
// create a class
class Room {
public:
double length;
double breadth;
double height;
Page 9 of 15
C++ Programming Handout 6
double calculateArea() {
return length * breadth;
}
double calculateVolume() {
return length * breadth * height;
}
};
int main() {
return 0;
}
Output
Area of Room = 1309
Volume of Room = 25132.8
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 calculateArea() and calculateVolume() 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.
As per our needs, we can also create private members using the private keyword. The private members
of a class can only be accessed from within the class. For example,
class Test {
private:
int a;
void function1() { }
public:
int b;
void function2() { }
}
Here, a and function1() are private. Thus they cannot be accessed from outside the class.
On the other hand, b and function2() are accessible from everywhere in the program.
Page 10 of 15
C++ Programming Handout 6
Example 2: Using public and private in C++ Class
// Program to illustrate the working of
// public and private in C++ Class
#include <iostream>
using namespace std;
class Room {
private:
double length;
double breadth;
double height;
public:
double calculateArea() {
return length * breadth;
}
double calculateVolume() {
return length * breadth * height;
}
};
int main() {
return 0;
}
Output
Area of Room = 1309
Volume of Room = 25132.8
The above example is nearly identical to the first example, except that the class variables are now private.
Since the variables are now private, we cannot access them directly from main(). Hence, using the
following code would be invalid:
// invalid code
obj.length = 42.5;
obj.breadth = 30.8;
obj.height = 19.2;
Instead, we use the public function initData() to initialize the private variables via the function
parameters double len, double brth, and double hgt.
Page 11 of 15
C++ Programming Handout 6
Member Functions in Classes
There are 2 ways to define a member function:
• Inside class definition
• Outside class definition
To define a member function outside the class definition we have to use the scope resolution :: operator
along with class name and function name.
// C++ program to demonstrate function
// declaration outside class
#include <iostream>
using namespace std;
class Geeks
{
public:
string geekname;
int id;
Geeks obj1;
obj1.geekname = "xyz";
obj1.id=15;
// call printname()
obj1.printname();
cout << endl;
// call printid()
obj1.printid();
return 0;
}
Output:
Geekname is: xyz
Geek id is: 15
Note that all the member functions defined inside the class definition are by default inline, but you can
also make any non-class function inline by using keyword inline with them. Inline functions are actual
functions, which are copied everywhere during compilation.
Page 12 of 15
C++ Programming Handout 6
Example: A program to demonstrate passing objects by value to a member function of the same class
#include<iostream.h>
//if you use iostream.h, there is no need to put “using namespace std;”
//Also you have to use “\n” instead of “endl”.
class weight {
int kilogram;
int gram;
public:
void getdata ();
void putdata ();
void sum_weight (weight,weight) ;
} ;
void weight :: getdata() {
cout<<"/nKilograms:";
cin>>kilogram;
cout<<"Grams:";
cin>>gram;
}
void weight :: putdata () {
cout<<kilogram<<" Kgs. and"<<gram<<" gros.\n";
}
void weight :: sum_weight(weight w1,weight w2) {
gram = w1.gram + w2.gram;
kilogram=gram/1000;
gram=gram%1000;
kilogram+=w1.kilogram+w2.kilogram;
}
int main () {
weight w1,w2 ,w3;
cout<<"Enter weight in kilograms and grams\n";
cout<<"\n Enter weight #1" ;
w1.getdata();
cout<<" \n Enter weight #2" ;
w2.getdata();
w3.sum_weight(wl,w2);
cout<<"/n Weight #1 = ";
w1.putdata();
cout<<"Weight #2 = ";
w2.putdata();
cout<<"Total Weight = ";
w3.putdata();
return 0;
}
Page 13 of 15
C++ Programming Handout 6
however, they can re passed by reference also. For example, to pass w1 and w2 by reference to the
function sum_weight the function will be declared and defined as:
// body of function
class employee
{
int emp_num;
char emp_name[20];
float emp_basic;
float sal;
float emp_da;
float net_sal;
float emp_it;
public:
void get_details();
void find_net_sal();
void show_emp_details();
};
Page 14 of 15
C++ Programming Handout 6
cout<<"\nBasic salary : "<<emp_basic;
cout<<"\nEmployee DA : "<<emp_da;
cout<<"\nIncome Tax : "<<emp_it;
cout<<"\nNet Salary : "<<net_sal;
}
int main()
{
employee emp[10];
int i,num;
clrscr();
for(i=0;i<num;i++)
emp[i].get_details();
for(i=0;i<num;i++)
emp[i].find_net_sal();
for(i=0;i<num;i++)
emp[i].show_emp_details();
getch();
return 0;
}
Page 15 of 15