0% found this document useful (0 votes)
3 views

Class and Objects

What is class and object in c++ Difference between class and object in c++
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Class and Objects

What is class and object in c++ Difference between class and object in c++
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

Object and Class in C++

9/24/2024 Dr. ASHISH KUMAR SAHU 1


Outline
• Basics of Object and Class in C++
• Private and Public Members
• Constructors and their types
• Destructors
• Operator Overloading

9/24/2024 Dr. ASHISH KUMAR SAHU 2


What is an Object?

Pen Board Laptop

Bench Projector Bike

Physical objects…

9/24/2024 Dr. ASHISH KUMAR SAHU 3


What is an Object? (Cont…)

Result Bank
Account
Logical objects…

9/24/2024 Dr. ASHISH KUMAR SAHU 4


Attributes and Methods of an Object

Bank Account

Object: Person Object: Car Object: Account

Attributes Attributes Attributes


Name Company AccountNo
Age Color HolderName
Weight Fuel type AccountType
Methods Methods Methods
Eat Start Deposit
Sleep Drive Withdraw
Walk Stop Transfer

9/24/2024 Dr. ASHISH KUMAR SAHU 5


Class

A Class is a blueprint of an object

A Class describes the object

9/24/2024 Dr. ASHISH KUMAR SAHU 6


Class car

Class: Car

9/24/2024 Dr. ASHISH KUMAR SAHU 7


Class: Car

Properties (Describe)
Company Methods (Functions)
Model Start
Color Drive
Mfg. Year Park
Price On_break
Fuel Type On_lock
Mileage On_turn
Gear Type
Power Steering
Anti-Lock braking system

9/24/2024 Dr. ASHISH KUMAR SAHU 8


Objects of Class Car

Honda City Hyundai i20 Sumo


Grand

Mercedes E class Swift Dzire

9/24/2024 Dr. ASHISH KUMAR SAHU 9


Class in C++
• A class is a blueprint or template that describes the object.
• A class specifies the attributes and methods of objects.

Example:
class car
{
// data members and member functions
}car1;
▪ In above example class name is car, and car1 is object of that class.

9/24/2024 Dr. ASHISH KUMAR SAHU 10


Specifying Class

How to declare / write class ?

How to create an object


(instance/variable of class)?

How to access class members ?

9/24/2024 Dr. ASHISH KUMAR SAHU 11


How to declare / write class ?

Class
class car
{ Car
private:
int price; Attributes
float mileage; Price
public: Mileage
void start(); Methods
void drive(); Start
}; Drive

9/24/2024 Dr. ASHISH KUMAR SAHU 12


How to create an object ?
Syntax:
className objectVariableName;

Class
class car
{
Object
private:
int main()
int price;
{
float mileage;
public: car c1;
void start(); c1.start();
void drive(); }
};

9/24/2024 Dr. ASHISH KUMAR SAHU 13


Object in C++
• An object is an instance of a class
• An object is a variable of type class

Class Object
class car
{ int main()
private: {
int price; car c1;
float mileage; c1.start();
public: c1.drive();
void start(); }
void drive();
};

9/24/2024 Dr. ASHISH KUMAR SAHU 14


Program: class, object

• Write a C++ program to create class Test having data members mark
and spi.
• Create member functions SetData() and DisplayData()to
demonstrate class and objects.

9/24/2024 Dr. ASHISH KUMAR SAHU 15


#include <iostream>
using namespace std;
Program: class, object
class Test
{ int main()
private: {
int mark; Test o1;
float spi; o1.SetData();
public: o1.DisplayData();
void SetData() return 0;
{ }
mark = 270; ▪ Calling
Executes
Creates statements
Startingmember
point
an ao1and
offunction.
object of
spi = 6.5; return to calling
tofunction
type
Control
Program Test
jumps
}
definition of SetData()
void DisplayData()
DisplayData()
{
cout << "Mark= "<<mark<<endl;
cout << "spi= "<<spi;
}
} ;

9/24/2024 Dr. ASHISH KUMAR SAHU 16


class Test int main()
{ {
private: Test o1,o2;
int mark; o1.SetData();
float spi; o1.DisplayData();
public: o2.SetData();
void SetData() o2.DisplayData();
{ return 0;
cin>>mark; }
cin>>spi;
} mark = 50
void DisplayData() o1
{
spi = 7.5
cout << "Mark= "<<mark;
cout << "spi= "<<spi;
} mark = 70
} ;
o2
spi = 6.83

9/24/2024 Dr. ASHISH KUMAR SAHU 17


Program: class, object

• Write a C++ program to create class Car having


• data members
• Company
• Top_Speed.
• Create member functions SetData() and DisplayData() and
create two objects of class Car.

9/24/2024 Dr. ASHISH KUMAR SAHU 18


class Car
{ Program: class, object
private: int main()
char company[20]; {
int top_speed; Car o1;
public: o1.SetData();
void SetData(){ o1.DisplayData();
cout<<"Enter Company:"; return 0;
cin>>company; }
cout<<"Enter top speed:";
cin>>top_speed;
}
void DisplayData()
{
cout << "\nCompany:"<<company;
cout << "\tTop Speed:"<<top_speed;
}
} ;

9/24/2024 Dr. ASHISH KUMAR SAHU 19


Program: class, object

• Write a C++ program to create class Employee having data members


Emp_Name, Salary, Age.
• Create member functions SetData() and DisplayData().
• Create two objects of class Employee

9/24/2024 Dr. ASHISH KUMAR SAHU 20


class Employee
{
Program: class, object
private:
char name[10];
int salary, age; int main()
{
public: Employee o1;
void SetData() o1.SetData();
{ o1.DisplayData();
cin>>name>>salary>>age; return 0;
} }
void DisplayData()
{
cout << “Name= "<<name<<endl;
cout << “salary= "<<salary<<endl;
cout << “age= "<<age;
}
} ;

9/24/2024 Dr. ASHISH KUMAR SAHU 21


Private and Public Members

Private Public

9/24/2024 Dr. ASHISH KUMAR SAHU 22


Private Members

▪ByPrivate
defaultmembers of the class
all the members of can be
class
Class accessed within the class and from
are private
member functions of the class.
▪ A private member variable or
class car
function cannot be accessed, or
{ Private: even viewed from outside the class.
long int price;
float mileage;
void setdata() This feature in OOP is known as
{ Data hiding / Encapsulation
price = 700000;
mileage = 18.5;
}
};

9/24/2024 Dr. ASHISH KUMAR SAHU 23


Private Members

• Private members of the class can be accessed within the class and
from member functions of the class.
• They cannot be accessed outside the class or from other programs,
not even from inherited class.
• If you try to access private data from outside of the class, compiler
throws error.
• This feature in OOP is known as Data hiding / Encapsulation.
• If any other access modifier is not specified then member default
acts as Private member.

9/24/2024 Dr. ASHISH KUMAR SAHU 24


Public Members
Class The public
Public members
members of a class from
are accessible can
class car beanywhere
accessed outside the class but
using
{ the objectwithin
nameaand dot operator '.'
program.
private:
long int price;
float mileage;
public: Object
char model[10];
int main()
void setdata()
{
{
price = 700000; car c1;
mileage=18.53; c1.model = "petrol";
} c1.setdata();
}; }

9/24/2024 Dr. ASHISH KUMAR SAHU 25


Public Members

• The public keyword makes data and functions public.


• Public members of the class are accessible by any program from
anywhere.
• Class members that allow manipulating or accessing the class data
are made public.

9/24/2024 Dr. ASHISH KUMAR SAHU 26


Data Hiding in Classes
CLAS
No entry to S Area
Private
Private area Data
X
Functions

Public Area
Entry allowed
to Data
Public area Functions

9/24/2024 Dr. ASHISH KUMAR SAHU 27


Example Class in C++
class Test By Default the members of a
{ private is a Keyword
class are private.
private:
int data1; Private data and functions
float data2; can be written here
public:
void function1()
{
public is a data1 = 2;
Keyword }
float function2() Public data and functions
{ can be written here
data2 = 3.5;
return data2;
}
};

9/24/2024 Dr. ASHISH KUMAR SAHU 28


Member Functions with
Arguments

9/24/2024 Dr. ASHISH KUMAR SAHU 29


Program: Function with argument

• Define class Time with members hour, minute and second.


Also define function to setTime() to initialize the members,
print() to display time. Demonstrate class Time for two objects.

9/24/2024 Dr. ASHISH KUMAR SAHU 30


Program: Function with argument

#include<iostream>
using namespace std;
class Time
{
private :
int hour, minute, second;
public :
void setTime(int h, int m, int s);
void print();
};

9/24/2024 Dr. ASHISH KUMAR SAHU 31


Program: Function with argument
void Time::setTime(int h, int m, int s)
{
hour=h;
minute=m;
second=s;
}
void Time::print()
{
cout<<"hours=\n"<<hour;
cout<<"minutes=\n"<<minute;
cout<<"seconds=\n"<<second;
}

9/24/2024 Dr. ASHISH KUMAR SAHU 32


Program: Function with argument
int main()
{
int h,m,s;
Time t1;
cout<<"Enter hours="; cin>>h;
cout<<"Enter minutes="; cin>>m;
cout<<"Enter seconds="; cin>>s;

t1.setTime(h,m,s);
t1.print();
return 0;
}

9/24/2024 Dr. ASHISH KUMAR SAHU 33


Program: Function with argument

• Define class Rectangle with members width and height. Also


define function to set_values() to initialize the members,
area() to calculate area. Demonstrate class Rectangle for two
objects.

9/24/2024 Dr. ASHISH KUMAR SAHU 34


class Rectangle
{ Program: Function
int width, height;
public:
with argument
void set_values (int,int);
int area(){
return width*height;
}
};
void Rectangle::set_values (int x, int y){
width = x; height = y;
}
int main(){
Rectangle rect;
rect.set_values(3,4);
cout << "area: " << rect.area();
return 0;
}

9/24/2024 Dr. ASHISH KUMAR SAHU 35


Program: Function with argument

• Define class Employee with members age and salary.


1. Also define function to setdata() to initialize the members.
2. Define function displaydata() to display data.
3. Demonstrate class Employee for two objects.
int main(){
Employee yash,raj;
yash.setData(23,1500);
yash.displaydata();

raj.setData(27,1800);
raj. displaydata();
return 0;
}

9/24/2024 Dr. ASHISH KUMAR SAHU 36


Program: Function with
class Employee{ argument
private :
int age; int salary;
public :
void setData(int , int);
void displaydata();
};
void Employee::setData(int x, int y){
age=x;
salary=y;
}
void Employee::displaydata(){
cout<<"age="<<age<<endl;
cout<<"salary="<<salary<<endl;
}

9/24/2024 Dr. ASHISH KUMAR SAHU 37


Memory allocation of objects

• The member functions are created and placed in the memory space
only once at the time they are defined as part of a class specification.
• No separate space is allocated for member functions when the
objects are created.
• Only space for member variable is allocated separately for each
object because, the member variables will hold different data values
for different objects.

9/24/2024 Dr. ASHISH KUMAR SAHU 38


Memory allocation of objects(Cont…)
Common for all objects
Member function 1

Member function 2

Memory created when, Functions defined

Object 1 Object 2 Object 3


Member variable 1 Member variable 1 Member variable 1

Member variable 2 Member variable 2 Member variable 2

Memory created when Object created

9/24/2024 Dr. ASHISH KUMAR SAHU 39


class Account Object A1
{
Account No 101
int Account_no,Balance;
char Account_type[10]; Account Type Current
public: Balance 3400
void setdata(int an,char at[],int
bal)
Object A2
{
Account_no = an; Account No 102
Account_type = at; Account Type Saving
Balance = bal;
Balance 150
}
};
Object A3
int main(){
Account A1,A2,A3; Account No 103
A1.setdata(101,“Current“,3400); Account Type Current
A2.setdata(102,“Saving“,150);
Balance 7900
A3.setdata(103,“Current“,7900);
return 0;
}

9/24/2024 Dr. ASHISH KUMAR SAHU 40


Constructors

9/24/2024 Dr. ASHISH KUMAR SAHU 41


What is constructor ?
A constructor is a block of code which is,
similar to member function
has same name as class name
called automatically when object of class created

A constructor is used to initialize the objects of class as soon as the


object is created.

9/24/2024 Dr. ASHISH KUMAR SAHU 42


Constructor
class car class car
{ Same {
private: private:
name as
float mileage; float mileage;
public: class name public:
void setdata() car()
{ Similar to {
cin>>mileage; member cin>>mileage;
} function }
}; };

int main() Called int main()


{ automaticall {
car c1;
c1,c2; y on car c1,c2;
c1;
c1.setdata(); creation of
c2.setdata(); object
} }

9/24/2024 Dr. ASHISH KUMAR SAHU 43


Properties of Constructor
• Constructor should be declared in class car
{
public section because private private:
constructor cannot be invoked float mileage;
outside the class so they are useless. public:
car()
• Constructors do not have return {
types and they cannot return values, cin>>mileage;
not even void. }
};

▪ Constructors cannot be inherited, even though a derived class


can call the base class constructor.
▪ Constructors cannot be virtual.
▪ They make implicit calls to the operators new and delete when
memory allocation is required.

9/24/2024 Dr. ASHISH KUMAR SAHU 44


Constructor (Cont…)
class Rectangle
{
int width,height;
public:
Rectangle(){
width=5;
height=6;
cout<<”Constructor Called”;
}
};
int main()
{
Rectangle r1;
return 0;
}

9/24/2024 Dr. ASHISH KUMAR SAHU 45


Types of Constructors

9/24/2024 Dr. ASHISH KUMAR SAHU 46


Types of Constructors

1) Default constructor
2) Parameterized constructor
3) Copy constructor

9/24/2024 Dr. ASHISH KUMAR SAHU 47


1) Default Constructor
• Default constructor is the one which invokes by default
when object of the class is created.
• It is generally used to initialize the default value of the
data members.
• It is also called no argument constructor.

class demo{ int main()


int m,n; { Object
public: d1
demo d1; m n
demo() }
{ 10 10
m=n=10;
}
};

9/24/2024 Dr. ASHISH KUMAR SAHU 48


Program Constructor
class Area int main(){
{ Area A1;
private: A1.Calculate();
int length, breadth; Area A2;
public: A2.Calculate();
Area(){ return 0;
length=5; }
breadth=2;
}
void Calculate(){
cout<<"\narea="<<length * breadth;
} A1 A2
}; breadt breadt
length length
h h
5 2 5 2

9/24/2024 Dr. ASHISH KUMAR SAHU 49


2) Parameterized Constructor

• Constructors that can take arguments are called parameterized


constructors.
• Sometimes it is necessary to initialize the various data elements of
different objects with different values when they are created.
• We can achieve this objective by passing arguments to the
constructor function when the objects are created.

9/24/2024 Dr. ASHISH KUMAR SAHU 50


Parameterized Constructor
▪ Constructors that can take arguments are called parameterized
constructors.
class demo
{
int m,n;
public:
demo(int x,int y){ //Parameterized Constructor
m=x;
n=y;
cout<<“Constructor Called“;
}
};
int main()
d1
{ m n
demo d1(5,6);
} 5 6

9/24/2024 Dr. ASHISH KUMAR SAHU 51


Program Parameterized Constructor

• Create a class Distance having data members feet and inch.


Create parameterized constructor to initialize members feet and
inch.

9/24/2024 Dr. ASHISH KUMAR SAHU 52


3) Copy Constructor

• A copy constructor is used to declare and initialize an object from


another object using an object as argument.
• For example:
demo(demo &d); //declaration
demo d2(d1); //copy object
OR demo d2=d1; //copy object
• Constructor which accepts a reference to its own class as a
parameter is called copy constructor.

9/24/2024 Dr. ASHISH KUMAR SAHU 53


3) Copy Constructor
• A copy constructor is used to initialize an object
from another object
using an object as argument.
▪ A Parameterized constructor which accepts a reference to its own
class as a parameter is called copy constructor.

9/24/2024 Dr. ASHISH KUMAR SAHU 54


Copy Constructor
class demo int main()
{ {
int m, n; demo obj1(5,6);
public: demo obj2(obj1);
demo(int x,int y){ demo obj2 = obj1;
m=x; }
n=y;
obj1
obj1 or x
cout<<"Parameterized Constructor";
} m n
demo(demo &x){ 5 6
m = x.m;
n = x.n; obj2
cout<<"Copy Constructor";
} m n
}; 5 6

9/24/2024 Dr. ASHISH KUMAR SAHU 55


Program: Types of Constructor

• Create a class Rectangle having data members length and


width. Demonstrate default, parameterized and copy constructor to
initialize members.

9/24/2024 Dr. ASHISH KUMAR SAHU 56


Program: Types of Constructor
class rectangle{
int length, width; This is constructor
public: overloading
rectangle(){ // Default constructor
length=0;
width=0;
}
rectangle(int x, int y){// Parameterized
constructor
length = x;
width = y;
}
rectangle(rectangle &_r){ // Copy constructor
length = _r.length;
width = _r.width;
}
};

9/24/2024 Dr. ASHISH KUMAR SAHU 57


Program: Types of Constructor (Cont…)

int main()
{
rectangle r1; // Invokes default constructor
rectangle r2(10,20); // Invokes parameterized
constructor
rectangle r3(r2); // Invokes copy constructor
}

9/24/2024 Dr. ASHISH KUMAR SAHU 58


Destructor

9/24/2024 Dr. ASHISH KUMAR SAHU 59


Destructor class car
{
• Destructor is used to destroy the objects float mileage;
that have been created by a constructor. public:
car(){
• The syntax for destructor is same as that cin>>mileage;
for the constructor, }

• the class name is used for the name of ~car(){


destructor, cout<<" destructor";
• with a tilde (~) sign as prefix to it. }

};

Destructor
▪ never takes any argument nor it returns any value nor it has
return type.
▪ is invoked automatically by the complier upon exit from the
program.
▪ should be declared in the public section.

9/24/2024 Dr. ASHISH KUMAR SAHU 60


Program: Destructor
class rectangle int main()
{ {
int length, width; rectangle x;
public: // default
rectangle(){ //Constructor constructor is
length=0; called
width=0; }
cout<<”Constructor Called”;
}
~rectangle() //Destructor
{
cout<<”Destructor Called”;
}
// other functions for reading, writing and
processing can be written here
};

9/24/2024 Dr. ASHISH KUMAR SAHU 61


Program: Destructor
class Marks{ int main( )
public: {
int maths; Marks m1;
int science; Marks m2;
//constructor return 0;
Marks() { }
cout << "Inside Constructor"<<endl;
cout << "C++ Object created"<<endl;
}
//Destructor
~Marks() {
cout << "Inside Destructor"<<endl;
cout << "C++ Object destructed"<<endl;
}
};

9/24/2024 Dr. ASHISH KUMAR SAHU 62


Operator Overloading

9/24/2024 Dr. ASHISH KUMAR SAHU


Operator Overloading
int a=5, b=10,c; Operator + performs
c = a + b; addition of
integer operands a, b

time t1,t2,t3; Operator + performs


t3 = t1 + t2; addition of
objects of type time

string str1=“Hello” Operator + concatenates


string str2=“Good Day”; two strings str1,str2
string str3;
str3 = str1 + str2;

9/24/2024 Dr. ASHISH KUMAR SAHU


Operator overloading
• Function overloading allow you to use same function name for
different definition.
• Operator overloading extends the overloading concept to
operators, letting you assign multiple meanings to C++
operators
• Operator overloading giving the normal C++ operators such as
+, * and == additional meanings when they are applied with
user defined data types.
Operator Purpose

Some of C++ * As pointer, As multiplication


Operators are already << As insertion, As bitwise shift left
overloaded
& As reference, As bitwise AND

9/24/2024 Dr. ASHISH KUMAR SAHU


Operator Overloading
int a=5, b=10,c;
c = a + b;
Operator + performs addition of integer
operands a, b
class time
{
int hour, minute;
}; Operator + performs addition of objects of
type time t1,t2
time t1,t2,t3;
t3 = t1 + t2;
string str1=“Hello”,str2=“Good Day”;
str1 + str2; Operator + concatenates two strings
str1,str2

9/24/2024 Dr. ASHISH KUMAR SAHU


Operator Overloading
• Specifying more than one definition for an operator in the
same scope, is called operator overloading.
• You can overload operators by creating “operator functions”.
Syntax:
return-type operator op-symbol(argument-list)
{
// statements
Keyword substitute the operator
}
Example:
void operator + (arguments);
int operator - (arguments);
class-name operator / (arguments);
float operator * (arguments);

9/24/2024 Dr. ASHISH KUMAR SAHU


Overloading Binary operator + int main()
class complex{ {
int real,imag; complex c1(4,6),c2(7,9);
public: complex c3;
complex(){ c3 = c1 + c2;
real=0; imag=0; c1.disp();
} c2.disp();
complex(int x,int y){ c3.disp();
real=x; imag=y; return 0;
} }
void disp(){
cout<<"\nreal value="<<real<<endl;
cout<<"imag value="<<imag<<endl;
}
complex operator + (complex);
};
complex complex::operator + (complex c){
complex tmp;
tmp.real = real + c.real; Similar to function call
tmp.imag = imag + c.imag; c3=c1.operator
return tmp; +(c2);
}

9/24/2024 Dr. ASHISH KUMAR SAHU


Binary Operator Arguments
result = obj1.operator symbol (obj2);//function notation
result = obj1 symbol obj2; //operator notation
complex operator + (complex x)
{
complex tmp;
tmp.real = real + x.real;
tmp.imag = imag + x.imag;
return tmp;
}

result = obj1.display();
void display()
{
cout<<"Real="<<real;
cout<<"Imaginary="<<imag;
}

9/24/2024 Dr. ASHISH KUMAR SAHU


Thank You

9/24/2024 Dr. ASHISH KUMAR SAHU 70

You might also like