Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

C++ Programming Handout 6

Object Oriented Programming in C++


Object Oriented Programming (OOP) involve the following concepts:
1. Objects
2. Class
3. Encapsulation
4. Abstraction
5. Polymorphism
6. Inheritance
Object-Oriented Programming is a methodology or paradigm to design a program using classes and
objects. It simplifies the software development and maintenance by providing some concepts:

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.

How to Create a Class and an Object


Class: To create a class, use the class keyword:
Example
Create a class called "MyClass":
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
Example explained
• The class keyword is used to create a class called MyClass.

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

// Access attributes and set values


myObj.myNum = 15;
myObj.myString = "Some text";

// Print attribute values


cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
}
Multiple Objects
You can create multiple objects of one class:
Example
// Create a Car class with some attributes
class Car {
public:
string brand;

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;

// Create another object of Car


Car carObj2;
carObj2.brand = "Ford";
carObj2.model = "Mustang";
carObj2.year = 1969;

// Print attribute values


cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year <<
"\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year <<
"\n";
return 0;
}

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

// Method/function definition outside the class


void MyClass::myMethod() {
cout << "Hello World!";
}

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 Car::speed(int maxSpeed) {


return maxSpeed;
}

int main() {
Car myObj; // Create an object of Car
cout << myObj.speed(200); // Call the method with an argument
return 0;
}

Access Specifiers in C++


Access specifiers in C++ define how the members of the class can be accessed. C++ has 3 new keywords
introduced, namely.
• public
• private
• protected
The table below shows how these specifiers are used in a class.

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();

cout<<"\nAccessing variable outside the class"<<endl;


//'a' cannot be accessed as it is private
//cout<<"value of a: "<<obj.a<<endl;

//'b' is public as can be accessed from any where


cout<<"value of b: "<<obj.b<<endl;

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

Accessing variable outside the class


Value of b: 20
Protected Access Specifier in C++
It is similar to private access specifier. It makes class member inaccessible outside the class. But they can
be accessed by any subclass of that class.
Syntax
class Protected_Access_Specifier
{
protected: // protected access specifier
int a; // Data Member Declaration
void display(); // Member Function Declaration
}
Access Specifier Example in C++
In below example shows all the three access specifiers public, private and protected.
#include<iostream>
using namespace std;

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;

//Every members can be access here, same class


cout<<"\nAccessing variable within the class"<<endl;

cout<<"Value of a: "<<a<<endl;
cout<<"Value of b: "<<b<<endl;
cout<<"Value of c: "<<c<<endl;
}
};

class Sub_class:public Declaration


{
public:
void show()
{
b=5;
c=6;
cout<<"\nAccessing variable in sub the class"<<endl;

// a is not accessible here it is private


//cout<<"Value of a: "<<a<<endl;
//b is public so it is accessible any where
cout<<"Value of b: "<<b<<endl;
//'c' is declared as protected, so it is accessible in sub class
cout<<"Value of c: "<<c<<endl;
}
};

void main()
{
clrscr();
Declaration d; // create object
d.show();

Sub_class s; // create object


s.show(); // Sub class show() function

cout<<"\nAccessing variable outside the class"<<endl;


//'a' cannot be accessed as it is private
//cout<<"value of a: "<<d.a<<endl;

//'b' is public as can be accessed from any where


cout<<"value of b: "<<d.b<<endl;

//'c' is protected and cannot be accesed here


//cout<<"value of c: "<<d.c<<endl;
getch();
}
Output
Accessing variable within the class
value of a: 10
value of b: 20
value of c: 30

Accessing variable in sub class


value of b: 5
value of c: 6

Page 8 of 15
C++ Programming Handout 6
Accessing variable outside the class
Value of b: 20

Accessing Data Members and Member Functions


Accessing Data Members
The public data members are also accessed in the same way given however the private data members are
not allowed to be accessed directly by the object. Accessing a data member depends solely on the access
control (Access Specifier) of that data member.

// C++ program to demonstrate


// accessing of data members

#include <iostream>
using namespace std;
class Geeks
{
// Access specifier
public:

// Data Members
string geekname;

// Member Functions()
void printname()
{
cout << "Geekname is: " << geekname;
}
};

int main() {

// Declare an object of class geeks


Geeks obj1;

// accessing data member


obj1.geekname = "Abhi";

// accessing member function


obj1.printname();
return 0;
}
Output:
Geekname is: Abhi

Example 1: Object and Class in C++ Programming


// Program to illustrate the working of
// objects and class in C++ Programming

#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() {

// create object of Room class


Room room1;

// assign values to data members


room1.length = 42.5;
room1.breadth = 30.8;
room1.height = 19.2;

// calculate and display the area and volume of the room


cout << "Area of Room = " << room1.calculateArea() << endl;
cout << "Volume of Room = " << room1.calculateVolume() << endl;

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:

// function to initialize private variables


void initData(double len, double brth, double hgt) {
length = len;
breadth = brth;
height = hgt;
}

double calculateArea() {
return length * breadth;
}

double calculateVolume() {
return length * breadth * height;
}
};

int main() {

// create object of Room class


Room room1;

// pass the values of private variables as arguments


room1.initData(42.5, 30.8, 19.2);

cout << "Area of Room = " << room1.calculateArea() << endl;


cout << "Volume of Room = " << room1.calculateVolume() << endl;

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;

// printname is not defined inside class definition


void printname();

// printid is defined inside class definition


void printid()
{
cout << "Geek id is: " << id;
}
};

// Definition of printname using scope resolution operator ::


void Geeks::printname()
{
cout << "Geekname is: " << geekname;
}
int main() {

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;
}

The output of the program is


Enter weight in kilograms and grams
Enter weight #1
Kilograms: 12
Grams: 560
Enter weight #2
Kilograms: 24
Grams: 850
Weight #1 = 12 Kgs. and 560 gms.
Weight #2 = 24 Kgs. and 850 gms.
Total Weight = 37 Kgs. and 410 gms.
In this example, the sum_weight () function has direct access to the data members of calling object (w3 in
this case). However, the members of the objects passed as arguments (w1 and w2) can be accessed within
function using the object name and dot operator. Note that, the objects w1 and w2 are passed by value,

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:

void sum_weight (weight &,weight &) ;

void weight :: sum_weight (weight & w1, weight & w2) {

// body of function

Question: Given that an Employee class contains the following members:


Date Members: Employee_Number, Employee_Name, Basic, DA, IT, Net_Sal;
Member Function: to read data, to calculate Net_Sal and to print data members;
Write a C++ program to read data on N employees and compute the Net_Sal of each employee ( DA =
52% of Basic and Income Tax (IT) = 30% of the gross salary ).
Answer:
#include<iostream>
using namespace std;

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();
};

void employee :: get_details()


{
cout<<"\nEnter employee number:\n";
cin>>emp_num;
cout<<"\nEnter employee name:\n";
cin>>emp_name;
cout<<"\nEnter employee basic:\n";
cin>>emp_basic;
}

void employee :: find_net_sal()


{
emp_da=0.52*emp_basic;
emp_it=0.30*(emp_basic+emp_da);
net_sal=(emp_basic+emp_da)-emp_it;
}

void employee :: show_emp_details()


{
cout<<"\n\n\nDetails of : "<<emp_name;
cout<<"\n\nEmployee number: "<<emp_num;

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();

cout<<"\nEnter number of employee details\n";


cin>>num;

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;
}

Next: Constructors and Destructors

Page 15 of 15

You might also like