[go: up one dir, main page]

0% found this document useful (0 votes)
27 views25 pages

C++ - CLASSES

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views25 pages

C++ - CLASSES

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Classes: Introduction, Defining an Instance of a Class, Why Have Private Members?

Separating Class Specification from Implementation, Inline Member Functions,


Constructors, Passing Arguments to Constructors, Destructors, Overloading
Constructors, Private Member Functions, Arrays of Objects, Instance and Static
Members, Friends of Classes, Member-wise Assignment, Copy Constructors,
Operator Overloading, Object Conversion, Aggregation.

​ CLASSES

​ Before you create an object in C++, you need to define a class.

​ A class is a blueprint for the object.

​ Eg: We can think of class as a sketch (prototype) of a house.


It contains all the details about the floors, doors, windows
etc. Based on these descriptions we build the house. House is
the object. As, many houses can be made from the same
description, we can create many objects from a class.
​ A class needs to be defined before an object can be created.

​ An object an instance of a class.

​ Introduction

​ Classes are the most important feature of C++ that leads to


object oriented programming.
​ ​Class is a user defined data type, which holds its own data

members and member functions, which can be accessed and


used for creating instance of that class.
​ The variables inside class definition are called as data
members and the functions are called member
functions.
​ A class is defined in C++ using keyword class followed by the name of class.
​ The body of class is defined inside the curly brackets and
terminated by a semicolon at the end.

Syntax of declaring class


class class-name
{
d
a
t
a
t
y
p
e
v
a
r
1
;
d
a
t
a
t
y
p
e
v
a
r
2
;
----------
datatype varN;

m
e
t
h
o
d
1
(
)
;
m
e
t
h
o
d
2
(
)
;
----------
methodN();
};

Example of declaring class


class Employee
{
int Id;
char Name[25];
int Age;
long Salary;

public:
void GetData();
void PutData();
};

​ In the above program a class named employee is defined.

​ This class has data members: Id, Name, Age and Salary, two member
functions: GetData() and PutData().
​ The private keyword makes data and functions private, by default the data
member and member functions are private.
​ Private data and functions can be accessed only from inside the same class.

​ The public keyword makes data and function public. Public data and functions
can be accessed out of the class.
​ Here, Id, Name, Age and Salary are private members where as GetData() and
PutData() are public members.
​ If we try to access private data from outside of the class, complier throws
error.
​ This feature in OOP is known as data hiding.

​ Defining an instance of a class

​ An object is an instance of a class.

​ ​When 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.
​ Instantiation of object means, create an object of class to access
its members. Object is a variable of class type.
​ Class members are accessed using the dot operator (.) between class’s object
and class’s member name.

Syntax for creating an object of class – class-name obj;


Example for creating an object of employee class is as follows:
class Employee
{
int Id;
char Name[25];
int Age;
long Salary;

public:
void GetData();
void PutData();
};
int main()
{
Employee Emp;
}

In above example, an object(Emp) is created of class Employee.

​ Defining Class Member Functions

We can define member function in 2 ways –

1.​ Inside the class


2.​ Outside the class

1.​ Defining member function inside the

class Syntax:

return_type function_name(argument list)


{
Body of function

▪​ return_type: type of value function will return.


▪​ function_name: can be any valid C++ identifier.
▪​ ​Argument list: represents the type and number of value function will
take, value are sent by the calling statement.

▪​ Definition of member function class is similar to defining normal function.

▪​ There is no need to tell complier about the class the function belongs to
because the definition of member function is already in the class.

Program
#include<iostream>
Using namespace std;
#include<conio.h>

class Employee
{
int Id;
char Name[25];
int Age;
long Salary;

public:
void GetData() //Defining GetData()
{
cout<<”Enter Employee Id:”;
cin>>Id;
cout<<”Enter Employee Name:”;
cin>>Name;
cout<<”Enter Employee Age:”;
cin>>Age;
cout<<”Enter Employee Salary:”;
cin>>Salary;
}
void PutData() //Defining PutData()
{
cout<<endl<<”Employee Id: ”<<Id<<endl;
cout<<endl<<”Employee Name: ”<<Name<<endl;
cout<<endl<<”Employee Age: ”<<Age<<endl;
cout<<endl<<”Employee Salary: ”<<Salary<<endl;
}
};
int main()
{
Employee E; //Creating Object
E.GetData(); //Calling GetData()
E.PutData();​ //Calling
PutData()
getch();
return 0;
}
Output:
Enter Employee Id: 101
Enter Employee Name: ABC
Enter Employee Age: 22
Enter Employee Salary:20000

Employee Id:101
Employee Name: ABC
Employee Age: 22
Employee Salary: 20000

▪​ In a above program, we have defined two member functions GetData() and


PutData() within main class.
▪​ In main(), we created an object E of employee class and invoke/call member
function through the object E of Employee class.
2.​ Defining member function inside the class

Syntax:

return_type class_name :: function_name(argument list)


{

Body of function
}

​ Return_type :Type of value function will return.

​ Class_name: a program may contain more than one class and these classes
may have similar member functions. Class_name:: tells the complier which class
the function belongs to and the scope of member function is restricted to the
class_name.
​ Function_name: can be any valid C++ identifier.

​ Argument list: represents the type and number of value function will take,
values are sent by the calling statement.

Example

#include<iostream>
Using namespace std;
#include<conio.h>

class Employee
{
int Id;
char Name[25];
int Age;
long Salary;

public:
void GetData();
void PutData();
};

void Employee::GetData() //Defining GetData()


{
cout<<”Enter Employee Id:”;
cin>>Id;
cout<<”Enter Employee Name:”;
cin>>Name;
cout<<”Enter Employee Age:”;
cin>>Age;
cout<<”Enter Employee Salary:”;
cin>>Salary;
}
void Employee::PutData() //Defining PutData()
{
cout<<endl<<”Employee Id: ”<<Id<<endl;
cout<<endl<<”Employee Name: ”<<Name<<endl;
cout<<endl<<”Employee Age: ”<<Age<<endl;
cout<<endl<<”Employee Salary: ”<<Salary<<endl;
}
};
int main()
{
Employee E; //Creating Object
E.GetData(); //Calling GetData()
E.PutData();​ //Calling
PutData()
getch();
return 0;
}
Output:
Enter Employee Id: 101
Enter Employee Name: ABC
Enter Employee Age: 22
Enter Employee Salary:20000

Employee Id:101
Employee Name: ABC
Employee Age: 22
Employee Salary: 20000

▪​ In a above program, we have declared two member functions GetData() and


PutData() within class and defined these methods outside the class.
▪​ In main(), we created an object E of employee class and invoke/call member
function through the object E of Employee class.

​ Constructors

​ A constructor is a special type of member function that initializes an object


automatically when it is created.
​ Constructor has the same name as that of the class and it does not have any
return type.
​ Compiler identifies a given member function is a constructor by its name and
the return type. Constructor is always public.
​ Characteristics of a constructor are-

1.​ Constructor name class name must be same.


2.​ Constructor doesn’t return value.
3.​ Constructor is invoked automatically, when the object of class is created.

Class A
{
int x;

public:
A(); //constructor
};

​ Constructor can be defined either inside the class definition or outside class
definition using class name and scope resolution:: operator.

Class A
{
int i; public:
A();//constructor declared
};

A::A() //Constructor definition


{
i=1;
}

​ Constructors are of 3 types –


1.​ Default constructor
2.​ Parameterized constructor
3.​ Copy constructor

1)​ Default Constructor – Default constructor is the constructor which doesn’t


take any argument. It has no parameter.
Syntax: class_name()
{Constructor Definition}
program

#include<iostream>
Using namespace std;
#include<conio.h>
Class Cube
{
int side;
public:
Cube()
{
Side=25;
}
int getSide()
{
return side;
}
};
int main()
{
Cube c;
cout<<” Value of side is ”<<c.getSide();
getch();
return 0;
}
Output: Value of side is 25

​ In the above program, as soon as the object is created the constructor is


called which initializes its data members.
​ A default constructor is so important for initialization of object members, that
even if we do not define a constructor explicitly, the complier will provide a
default constructor implicitly.
2)​ Parameterized constructor – these are the constructors with parameter. This
constructor is used to provide different values to data members of different
objects, by passing the appropriate values as argument.

Program
#include<iostream>
Using namespace std;
#include<conio.h>
Class Cube
{
int side;
public:
Cube(int x)
{
Side=x;
}
int getSide()
{
return side;
}
};
int main()
{
Cube c1(10);
Cube c2(20);
Cube c3(30);
cout<<Value of c1 side is: ”<<c1.getSide()<<endl;
cout<<Value of c2 side is: ”<<c2.getSide()<<endl;
cout<<Value of c3 side is: ”<<c3.getSide()<<endl;
getch();
return 0;
}

Output: Value of c1 side is: 10


Value of c2 side is: 20
Value of c3 side is: 30
​ By using parameterized constructor in the above program, we have initialized
3 objects with user defined values. We can have any number of parameters in
a constructor.

3)​ Copy constructor – copy constructor is special type of constructor which takes
an object as argument, and is used to copy values of data members of one
object into other object. A copy constructor takes a parameter which is
reference to its own class type.
Syntax:
ClassName(ClassName &old_obj);
Program- show the usage of copy constructor
#include<conio.h>
#include<string.h>
Class Student
{
int Roll;
char Name[25];
float Marks;

public:

Student(int r,char nm[],float m) //parameterized constructor


{
Roll=r;
Strcpy(Name,nm)
;
Marks = S.Marks;
}
Student(Student &S) //copy constructor
{
Roll=S.Roll;
Strcpy(Name,S.Name);
Marks = S.Marks;
}

void Display()
{
Cout<<”Roll: “<<Roll<<endl;
Cout<<”Name: “<<Name<<endl;

Cout<<”Marks: “<<Marks<<endl;
}
};
int main()
{
Student S1(1,”sam”,85.65);’
StudentS2(S1);​ //statement 1

Cout<<”Values in object S1”<<endl;


S1.Display();

Cout<<”Values in object S2”<<endl;


S2.Display();

Getch();
Return();
}

Output:
Values in object S1
Roll: 1
Name: sam
Marks: 85.65

Values in object S2
Roll: 2
Name: matt
Marks: 90.50

​ Operator overloading

​ An operator is a symbol that tells the complier to perform specific task.

​ Every operator has their own functionality to work with built-in data types.

​ Class is user defined data type and complier doesn’t understand how to use
operators with user-defined data types.
​ The function for operator is declared by using the operator keyword followed
by the operator.
​ To overload an operator, a special operator function is defined inside the
class as:
Syntax:
Class className
{
……
Public
returnType operator symbol(arguments)
{
………..
}

……
};

▪​ Here returnType is the returntype of the function.


▪​ The returntype of the function is followed by operator keyword
▪​ There 2 types of operator overloading
1.​ Binary operator overloading
2.​ Unary operator overloading

1.​ Binary operator overloading


▪​ Binary operator is an operator that takes 2 operand(variable).
▪​ Binary operators
1.​ Arithmetic operators(+,-,*,%,/)
2.​ Arithmetic assignment operators(+=,-=,*=,/=,%=)
3.​ relational operators (>,<,>=,<=,!=,==)
▪​ program – show the usage of overloading binary operator

#include<iostream>

Using namespace std;


#include<conio.h>
Class Rectangle
{
int L,B;
public:
Rectangle() //Default Constructor
{
L=0;
B=0;
}
Rectangle(int x,int y)​ //parameterize constructor
{
L=x;
B=y;
}
Rectangle operator+(Rectangle Rec) //operator overloading
{
Rectangle R
R.L=L+REC.L;
R.B=B+REC.B;
Return R;
}
void Display()
{
Cout<<”Length: “<<L<<”Breadth: “<<B<<endl;
}
};
int main()
{
Rectangle R1(2,5),R2(3,4),R3;
Cout<<”Rectangle 1: “;
R1.Display();

Cout<<”Rectangle 2: “;
R2.Display();

R3=R1+R2;
Cout<<”Rectangle 3: “;
R3.Display();

Getch();
Return();
}
Output:
Rectangle1: Length: 2 Breadth: 5
Rectangle2: Length: 3 Breadth: 4
Rectangle3: Length: 5 Breadth: 9

2.​Unary operator overloading

▪​ Unary operator is an operator that take single operand(variable).


▪​ Both increment(++) and decrement(--) operators are unary
▪​ program – show the usage of overloading Unary operator
#include<iostream>
Using namespace std;
#include<conio.h>

Class Rectangle
{
int L,B;

public:
Rectangle() //Default Constructor
{
L=0;
B=0;
}
void operator++() //operator overloading
{
L=L+2;
B=B+2;
}
void Display()
{
Cout<<”Length: “<<L<<”Breadth: “<<B<<endl;
}
};
int main()
{
Rectangle R;
Cout<<”Length Breadth before increment “<<endl;
R.Display();
++R
Cout<<”Length Breadth after increment “<<endl;
R.Display();

Getch();
Return();
}
Output:
Length Breadth before increment
Length: 0 Breadth: 0
Length Breadth after increment
Length: 2 Breadth: 2

​ Friends of classes

​ Important concept of OOP is Data hiding so nin member function cannot


access an objects private and protected data.
​ There is a mechanism built in C++ to access private & protected data from
non member function.
​ This is done using
1.​ Friend function
2.​ Friend class

​ Friend function : if a function is defined as a friend function then, the private


and protected data of a class can be accessed using the fuction. The complier
knows as a given function is a friend function by the use of the keyword friend.

Syntax:
Class class_name
{
………
Friend return_type
function_name(arguments);
……..
}
Program

Show the usage of friend function

#include<iostream>
Using namespace std;

#include<conio.h>

Class Distance

Private:

int meter;

public:

Distance():meter(0) { }

//friend function

Friend int addFive(Distance);


};
//friend function definition
int addFive(Distance d)
{
//accessing private data from non-member function

d.meter+=5;
return d.meter;
}
int main()
{
Distance D;
Cout<<”Distance is:”<<addFive(D);
Getch();
Return 0;
}

OUTPUT:
Distance is:5
In the above program, friend function addFive() is declared inside Distance class.
So, the private data variable meter can be accessed from this function.

2.​Friend class
▪​ Like a friend function, a class can also be made a friend of another class using
keyword friend.
▪​ When a class is made a friend class, all the member functions of that class
become friend functions.
▪​ Syntax:
……..
Class B;
Class A
{
//class B is a friend class of class A
Friend class B;
…….
}
Class B
{
…….
}

▪​ Program:
Show the usage of friend class

#include<iostream>

Using namespace std;

#include<conio.h>

Class Rectangle

int L,B;

public:

Rectangle() //created constructor default

L=10;

B=20;

}
friend class Square; //friend class

};
Class Square
{
int S;
public:
square()
{
S=5;
}
void Display(Rectangle Rect)
{
Cout<<”Length:”<<Rect.L<<endl;
Cout<<”Breadth:”<< Rect.L<<endl;
Cout<<”Side:”<< S<<endl;
}
};
int main()
{
Rectangle R;
Square S;
S.Display(R);

Getch();
Return 0;
}

OUTPUT:

Length: 10
Breadth: 20
Side: 5

In the above example, we have created two classes Rectangle and Square. In
order to access the private and protected members or Rectangle class by
Square class, we have made Square class, a friend class of Rectangle class.
Now, Square class access all data member and member functions of Rectangle
class.
​ Aggregation

▪​ Aggregation is a process in which one class defines another class as any


entity reference.
▪​ It is another way to reuse the class.

▪​ Program- usage of aggregation

#include<iostream>

Using namespace std;

#include<conio.h>

Class Address

Public:

Char addressline[30],city[30],state[30];

Address(char addressline[], char city[], char state[])

Strcpy(this->addressline, addressline);

Strcpy(this->city, city);

Strcpy(this->state, state);

};

Class Employee

Private:

Address*addresss; //Employee has a address

public:

int id

Char name[30];
Employee(int id,char name[],Address*address)
{
this->id=id;
strcpy(this->name,name);
this->address=address;
}
void Display()
{
Cout<<id<<” ”<<address->addressline<<” “;
Cout<<address->city<<” “<<address->state;

}
};

int main()
{
Address a1=Address(“Flat-104,Sec-2”,”Hyderabad”,”Telangana”);
Employee e1=Employee(102,”hash”,&a1);
E1.diaplay();
Getch();
Return 0;
}

OUTPUT:

You might also like