0% found this document useful (0 votes)
14 views30 pages

C++Unit2 Complete Notes

This document provides an overview of classes in C++, detailing their structure, member functions, access modifiers, and the concept of encapsulation. It explains the importance of public, private, and protected access modifiers, as well as the use of friend classes and functions. Additionally, it covers static members, constant member functions, and constructors, highlighting their roles in object-oriented programming.
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)
14 views30 pages

C++Unit2 Complete Notes

This document provides an overview of classes in C++, detailing their structure, member functions, access modifiers, and the concept of encapsulation. It explains the importance of public, private, and protected access modifiers, as well as the use of friend classes and functions. Additionally, it covers static members, constant member functions, and constructors, highlighting their roles in object-oriented programming.
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/ 30

UNIT-2

Class: A class in C++ is the building block, that leads to Object-Oriented


programming. It is a user-defined data type, which holds its own data members
and member functions, which can be accessed and used by creating an instance
of that class. A C++ class is like a blueprint for an object.

For Example: Consider the Class of Cars. There may be many cars with
different names and brand but all of them will share some common properties
like all of them will have 4 wheels, Speed Limit, Mileage range etc. So here, Car
is the class and wheels, speed limits, mileage are their properties.Here the data
member will be speed limit,mileage etc and member functions can be apply
brakes,increase speed etc.
Generally a class specification has two parts:
1.class declaration 2.class function definitions

The class declaration describes the type and scope of its members.The class
function definitions describe how the class function are implemented.
The general form of a class declaration is:
class class-name
{
Private:
Variable declarations;
Function declarations;
Public:
Variable declarations;
Function declarations;
};
The keyword class specifies that what follows is an abstract data of type
class_name.The body of a class is enclosed within braces and terminated by a
semicolon.The class body contains the declaration of variables and
functions.These functions and variables are collectively called class
members.They are usually grouped under two sections,namely,private and public
to denote which of the members are private and which of them are public.The
keywords private and public are known as visibility labels.
The class members that have been declared as
private can be accessed only from within the class.On the otherhand.public
members can be accessed from outside the class also.The data hiding(using
private declaration) is the key feature of object oriented programming.The use of
the keyword is optional.By default,the members of a class are private.If both the
labels are missing,then,by default all the members are private.such a class is
completely hidden from the outside world and doesn’t serve any purpose.
The variables declared inside the class are known
as data members and the functions are known as member functions.Only the
member functions can have access to the private data members and private
functions.However,the public members can be accessed from outside the
class.The binding of data and functions together into a single class-type variable
is referred to as Encapsulation.
Fig:

Class objects:An object is an instance of a class.once a class has been


declared,we can create variables of that type by using the class name.when a class
is defined,no memory is allocated but when it is instantiated memory is allocated.
Example: 1) item x,y,z; //memory for x,y,z are created.
2)item x;
Here memory for item x is created.
Accessing class members:
The private data of a class can be accessed only through the member functions of
that class.The following is the format for calling a member function.
Object-name.function-name(actual-arguments);
Example:
Class XYZ
{
int x;
int y;
public:
int z;
};
-----------------
-----------------
XYZ p;
p.z=10; // z is public,so it can be accessed
---------------
Defining Member functions:
Member functions can be defined in two places:
1.outside the class definition
2.Inside the class definition
outside the class definition: Member functions that are declared inside a class
have to be defined separately outside the class.Their definitions are very much
like the normal functions.They should have a function header and a function
body.
An important difference between a member function and a normal function is that
a member function incorporates a membership ‘identity label’ in the header.This
‘label’ tells the compiler which class the function belongs to.The general form of
a member function definition is
return-type class-name : : function name(argument declaration)
{
Function body
}
The membership label class-name : : tells the compiler that the function name
belong to the class class-name.That is the scope of the function is restricted to the
class-name specified in the header line.The symbol : : is called the scope
resolution operator.
Example:
void item : : getdata(int a,float b)
{
number = a;
cost = b;
}
void item : : putdata(void)
{
cout << “Number:” << number << “\n”;
cout << “cost:” << cost << “\n”;
}
Since these functions do not return any value,their return type is void.
The member functions have some special characteristics :
1.several different classes can use the same function name.The “membership
label” will resolve their scope.
2.Member functions can access the private data of the class.A non-member
function cannot do so.
3.A member function can call another member function directly,without using
the dot operator.
//program to display input value using classes
#include <iostream>
using namespace std;
class Programming
{
private:
int variable;
public:
void input_value()
{
cout<<"Enter input value\n";
cin>>variable;
}
void output_value()
{
cout<<"variable entered is:";
cout<<variable;
}
};
int main()
{
Programming obj;
obj.input_value();
obj.output_value();
return 0;
}
Output:Enter input value:
24
Variable entered is:24

/* C++ program to create a simple class and object.*/

#include <iostream>
using namespace std;

class Hello
{
public:
void sayHello()
{
cout << "Hello World" << endl;
}
};

int main()
{
Hello h;

h.sayHello();

return 0;
}

Output

Hello World

/*C++ program to create class for a student to get and print details of a student*/
#include <iostream>
using namespace std;

class student
{
private:
char name[30];
int rollNo;
int total;
float perc;
public:
//member function to get student's details
void getDetails(void);
//member function to print student's details
void putDetails(void);
};

//member function definition, outside of the class


void student::getDetails(void){
cout << "Enter name: " ;
cin >> name;
cout << "Enter roll number: ";
cin >> rollNo;
cout << "Enter total marks outof 500: ";
cin >> total;

perc=(float)total/500*100;
}

//member function definition, outside of the class


void student::putDetails(void){
cout << "Student details:\n";
cout << "Name:"<< name << ",Roll Number:" << rollNo << ",Total:" <<
total << ",Percentage:" << perc;
}

int main()
{
student std; //object creation

std.getDetails();
std.putDetails();

return 0;
}

Output

Enter name: mike


Enter roll number: 112
Enter total marks outof 500: 456
Student details:
Name:mike,Roll Number:112,Total:456,Percentage:91.2
//program to explain class and member functions
#include <iostream>
using namespace std;
class Item
{
int number;
float cost;
public:
void getdata(int a,float b);
void putdata()
{
cout<<"number:"<<number<<"\n";
cout<<"cost:"<<cost<<"\n";
}
};
void Item :: getdata(int a,float b)
{
number = a;
cost = b;
}
int main()
{
Item x;
x.getdata(100,299.95);
x.putdata();
return 0;
}
Output:
number: 100
cost: 299.5
this pointer in c++
The this pointer holds the address of current object.
#include <iostream>
using namespace std;
class Demo {
private:
int num;
char ch;
public:
void setMyValues(int num, char ch){
this->num =num;
this->ch=ch;
}
void displayMyValues(){
cout<<num<<endl;
cout<<ch;
}
};
int main(){
Demo obj;
obj.setMyValues(100, 'A');
obj.displayMyValues();
return 0;
}
Output:

100
A

Note: Here we can see that we have two data members num and ch. In member
function setMyValues() we have two local variables having same name as data
members name. In such case if you want to assign the local variable value to the
data members then you won’t be able to do until unless you use this pointer,
because the compiler won’t know that you are referring to object’s data members
unless you use this pointer.
Access Modifiers in C++
Access modifiers are used to implement an important aspect of Object-Oriented
Programming known as Data Hiding.
Access Modifiers or Access Specifiers in a class are used to assign the
accessibility to the class members. That is, it sets some restrictions on the class
members not to get directly accessed by the outside functions.
There are 3 types of access modifiers available in C++:

1.Public
2.Private
3.Protected

1. Public: All the class members declared under the public specifier will be
available to everyone. The data members and member functions declared as
public can be accessed by other classes and functions too. The public
members of a class can be accessed from anywhere in the program using the
direct member access operator (.) with the object of that class.
2. Private: The class members declared as private can be accessed only by the
member functions inside the class. They are not allowed to be accessed
directly by any object or function outside the class. Only the member
functions or the friend functions are allowed to access the private data
members of a class.
3. Protected: Protected access modifier is similar to private access modifier in
the sense that it can’t be accessed outside of it’s class unless with the help of
friend class, the difference is that the class members declared as Protected can
be accessed by any subclass(derived class) of that class as well.

Friend Class:

A friend class is a class that can access the private and protected members of a
class in which it is declared as friend. This is needed when we want to allow a
particular class to access the private and protected members of a class.

Function Class Example

In this example we have two classes XYZ and ABC. The XYZ class has two
private data members ch and num, this class declares ABC as friend class. This
means that ABC can access the private members of XYZ, the same has been
demonstrated in the example where the function disp() of ABC class accesses
the private members num and ch. In this example we are passing object as an
argument to the function.

#include <iostream>
using namespace std;
class XYZ {
private:
char ch=’A’;
int num=10;
public:
/* This statement would make class ABC
* a friend class of XYZ, this means that
* ABC can access the private and protected
* members of XYZ class.
*/
public:
friend class ABC;
};
class ABC
{
public:
void disp(XYZ obj)
{
cout<<obj.ch<<endl;
cout<<obj.num<<endl;
}
};
int main() {
ABC obj;
XYZ obj2;
obj.disp(obj2);
return 0;
}

Output:

A
10
Friend Function:
Similar to friend class, this function can access the private and protected
members of another class. A global function can also be declared as friend.
To make an outside function “friendly” to a class,we need to declare this
function as a friend of the class as shown below.

Class ABC
{
…………..
…………..
public :
…………….
…………….
friend void xyz(void); //declaration
};

The function declaration should be preceded by the keyword friend.The function


is defined elsewhere in the program like a normal c++ function.The function
definition does not use either the keyword friend or the scope operator : : The
functions that are declared with the keyword friend are known as friend
functons.A function can be declared as a friend in any number of classes.A friend
function,although not a member function,has full access rights to the private
members of the class.

Friend Function Example

#include <iostream>
using namespace std;
class XYZ {
private:
int num=100;
char ch='Z';
public:
friend void disp(XYZ obj);
};
//Global Function
void disp(XYZ obj){
cout<<obj.num<<endl;
cout<<obj.ch<<endl;
}
int main() {
XYZ obj;
disp(obj);
return 0;
}
Output:

100
Z

Static data members:

A data member of a class can be qualified as static.A static member variable has
certain special characteristics.They are:
1.It is initialized to zero when the first object of its class is created.No other
initialization is permitted.
2.only one copy of that member is created for the entire class and is shared by all
the objects of the class,no matter how many objects are created.
3.It is visible only within the class,but its lifetime is the entire program.

//program to explain static data member


#include<iostream>
using namespace std;
class Item
{
static int count;
int number;
public:
void getdata(int a)
{
number=a;
count++;
}
void getcount(void)
{
cout<<"count:";
cout<<count<<"\n";
}
};
int Item :: count;
int main()
{
Item a,b,c;
a.getcount();
b.getcount();
c.getcount();
a.getdata(100);
b.getdata(200);
c.getdata(300);
cout<<"After reading data"<<"\n";
a.getcount();
b.getcount();
c.getcount();
return 0;
}
Output:
count:0
count:0
count:0
After reading data
count:3
count:3
count:3

Explanation: The static variable count is initialized to zero when the objects are
created.The count is incremented whenever the data is read into an object.Since
the data is read into objects three times,the variable count is incremented three
times.Because there is only one copy of count shared by all the three objects,all
the the three output statements cause the value 3 to be displayed.

Static member functions:A member function that is declared static has the
following properties.
1.A static function can have access to only other static members declared in the
same class.
2.A static member function can be called using the class name as follows:
class-name :: function-name;

//Program to explain static function


#include<iostream>
using namespace std;
class Test
{
int code;
static int count;
public:
void setcode()
{
code=++count;
}
void showcode()
{
cout<<”object number:”<<code<<endl;
}
static void showcount()
{
cout<<”count:”<<count<<endl;
}
};
int Test :: count;
int main()
{
Test t1,t2;
t1.setcode();
t2.setcode();
Test::showcount();
Test t3;
t3.setcode();
Test::showcount();
t1.showcode();
t2.showcode();
t3.showcode();
return 0;
}
Output:
count:2
count:3
object number:1
object number:2
object number:3

Constant Member functions:

A constant (const) member function can be declared by using const keyword,


it is used when we want a function that should not be used to change the value
of the data members i.e. any type of modification is not allowed with the
constant member function.
#include <iostream>
using namespace std;

class Numbers
{
private:
int a;
int b;
public:
Numbers()
{
a = 0;
b = 0;
}

//setter functions to set a and b


void seta(int num1)
{
a = num1;
}
void setb(int num2)
{
b = num2;
}

//getter functions to get value of a and b


int geta(void) const
{
return a;
}
int getb(void) const
{
return b;
}
};

//Main function
int main()
{
//declaring object to the class
Numbers num;
//set values
num.seta(100);
num.setb(200);

//printing values
cout<<"Value of a: "<<Num.geta()<<endl;
cout<<"Value of b: "<<Num.getb()<<endl;

return 0;
}

Output

Value of a: 100
Value of b: 200

Constructors:

A constructor is a ‘special’ member function whose task is to initialize the objects


of its class.It is special because its name is same as the class name.The constructor
is invoked whenever an object of its associated class is created.It is called
constructor because it constructs the values of data members of the class.

Constructor vs Member function

Now that we know what is constructor, lets discuss how a constructor is


different from member function of the class.
1) Constructor doesn’t have a return type. Member function has a return type.
2) Constructor is automatically called when we create the object of the class.
Member function needs to be called explicitly using object of class.
3) When we do not create any constructor in our class, C++ compiler generates
a default constructor and insert it into our code. The same does not apply to
member functions.
A constructor is declared and defined as follows:

//class with a constructor


Class integer
{
int m,n;
public:
integer(void); //constructor declared
------------
------------
};
integer : :integer(void) //constructor defined
{
m=0;n=0;
}

When a class contains a constructor like the one defined above,it is guaranteed
that an object created by the class will be initialized automatically.

Example : integer int1; //object int1 created

Not only creates the object int1 of type integer but also initializes its data
members m and n to zero.There is no need to write any statement to invoke the
constructor function.

Types of constructors in c++ :


There are 3 types of constructors in c++
1.Default constructor
2.Parameterized constructor
3.Copy constructor

Default constructor: A constructor that accepts no parameter is called default


constructor.when you don’t specify any constructor in the class,a default
constructor with no code would be inserted into your code by the compiler.

class XYZ
{
....
XYZ()
{
//Empty no code
}
};
//program on default constructor
#include <iostream>
using namespace std;
class constructorDemo
{
public:
int num;
char ch;
constructorDemo()
{
num = 100;
ch = 'A';
}
};
int main()
{
constructorDemo obj;
cout<<"num: "<<obj.num<<endl;
cout<<"ch: "<<obj.ch;
return 0;
}
Output:

num: 100
ch: A

2) Parameterized Constructor

Constructors with parameters are known as Parameterized constructors. These


type of constructor allows us to pass arguments while object creation.

//program to explain parameterized constructor

#include <iostream>
using namespace std;
class Add{
public:
//Parameterized constructor
Add(int num1, int num2) {
cout<<(num1+num2)<<endl;
}
};
int main(void)
{

Add obj1(10, 20);


Add obj2 = Add(50, 60);
return 0;
}
Output:

30
110

// CPP program to illustrate


// parameterized constructors

#include <iostream>
using namespace std;
class Point
{
private:
int x, y;

public:
Point(int x1, int y1)
{
x = x1;
y = y1;
}

int getX()
{
return x;
}
int getY()
{
return y;
}
};

int main()
{
// Constructor called
Point p1(10, 15);
// Access values assigned by constructor
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();

return 0;
}
Output:

p1.x = 10, p1.y = 15


When an object is declared in a parameterized constructor, the initial values have
to be passed as arguments to the constructor function. The normal way of object
declaration may not work. The constructors can be called explicitly or implicitly.
Example e = Example(0, 50); // Explicit call
Example e(0, 50); // Implicit call

Copy constructor:
A copy constructor is a member function which initializes an object using another
object of the same class. A copy constructor has the following general function
prototype:
ClassName (const ClassName &old_obj);

Syntax: Copy Constructor Declaration In Main Function

// In Main Function
class_name object1(params);

Method 1 - Copy Constrcutor


class_name object2(object1);

Method 2 - Copy Constrcutor


class_name object3 = object1;

/* Example Program for Copy Constructor Overloading in C++


#include<iostream>
#include<conio.h>
using namespace std;
class Example
{
// Member Variable Declaration
int a, b;
public:
//Normal Constructor with Argument
Example(int x, int y)
{
// Assign Values In Constructor
a = x;
b = y;
cout << "\nIm Constructor";
}

//Copy Constructor with Obj Argument

Example(const Example& obj)


{
// Assign Values In Constructor
a = obj.a;
b = obj.b;
cout << "\nIm Copy Constructor";
}

void Display()
{
cout << "\nValues :" << a << "\t" << b;
}
};

int main() {
//Normal Constructor Invoked
Example Object(10, 20);

//Copy Constructor Invoked - Method 1


Example Object2(Object);

//Copy Constructor Invoked - Method 2


Example Object3 = Object;
Object.Display();
Object2.Display();
Object3.Display();
// Wait For Output Screen
getch();
return 0;
}

Output
Im Constructor
Im Copy Constructor
Im Copy Constructor
Values :10 20
Values :10 20

Values :10 20

Destructor in c++

A destructor is a special member function that works just opposite to


constructor, unlike constructors that are used for initializing an object,
destructors destroy (or delete) the object

Syntax of Destructor

~class_name()
{
//Some code
}
Similar to constructor, the destructor name should exactly match with the class
name. A destructor declaration should always begin with the tilde(~) symbol as
shown in the syntax above.

Destructor rules

1) Name should begin with tilde sign(~) and must match class name.
2) There cannot be more than one destructor in a class.
3) Unlike constructors that can have parameters, destructors do not allow any
parameter.
4) They do not have any return type, just like constructors.
5) When you do not specify any destructor in a class, compiler generates a
default destructor and inserts it into your code.
Destructor Example

#include <iostream>
using namespace std;
class HelloWorld{
public:
//Constructor
HelloWorld(){
cout<<"Constructor is called"<<endl;
}
//Destructor
~HelloWorld(){
cout<<"Destructor is called"<<endl;
}
//Member function
void display(){
cout<<"Hello World!"<<endl;
}
};
int main(){
//Object created
HelloWorld obj;
//Member function called
obj.display();
return 0;
}
Output:

Constructor is called
Hello World!
Destructor is called

Dynamic creation and destruction of objects:

c++ supports dynamic memory allocation/deallocation.It allocates memory and


initializes the memory variables.An object can be created at run time;such an
object is called a dynamic object.The construction and destruction of the dynamic
object is explicitly done by the programmer.The new and delete operators are
used to allocate and deallocate memory to such objects.A dynamic object can be
created using the new operator as follows:
ptr = new classname;

The new operator returns the address of the object created,and it is stored in the
pointer ptr.The variable ptr is a pointer object of the same class.The member
variable of the object can be accessed using the pointer and →(arrow) operator.
A dynamic object can be destroyed using the delete operator as follows:

delete ptr;

The delete operator destroys the object pointed by the pointer ptr.It also invokes
the destructor of a class.The following program explains the creation and
destruction of dynamic objects.

//program to create dynamic object


#include<iostream>
using namespace std;
class Data
{
private:
int x,y;
public:
Data()
{
x=10;
y=20;
cout<<"iam a constructor"<<endl;
}
~Data()
{
cout<<"iam a destructor"<<endl;
}
void display()
{
cout<<"x="<<x<<endl;
cout<<"y="<<y<<endl;
}
};
int main()
{
Data *d;
d = new Data;
d -> display();
delete d;
return 0;
}

Output:
iam a constructor
x=10
y=20
iam a destructor

Data Abstraction in C++: Data abstraction is one of the most essential and
important feature of object oriented programming in C++. It refers to providing
only essential information about the data to the outside world, hiding the
background details or implementation.

We can implement abstraction using access specifiers.The members that defines


the internal implementation can be marked as private in a class.The important
information needed to be given to the outside world can be marked as public.These
public members can access the private members as they are inside the class.

//program to explain data abstraction


#include <iostream>
using namespace std;
class implementAbstraction
{
private:
int a, b;

public:

// method to set values of


// private members
void set(int x, int y)
{
a = x;
b = y;
}

void display()
{
cout<<"a = " <<a << endl;
cout<<"b = " << b << endl;
}
};
int main()
{
implementAbstraction obj;
obj.set(10, 20);
obj.display();
return 0;
}

Output:
a = 10
b = 20

Explanation: we can see in the above program we are not allowed to access the
variables a and b directly, however one can call the function set() to set the values
in a and b and the function display() to display the values of a and b.

Advantages of Data Abstraction:


1.Helps the user to avoid writing the low level code
2.Avoids code duplication and increases reusability.
3.Can change internal implementation of class independently without affecting
the user.
4.Helps to increase security of an application or program as only important
details are provided to the user.

Abstract Data type (ADT) is a type (or class) for objects whose behaviour is
defined by a set of value and a set of operations. It is called “abstract” because
it gives an implementation-independent view. The process of providing only the
essentials and hiding the details is known as abstraction.
The user of data type does not need to know how that data type is implemented,
for example, we have been using Primitive values like int, float, char data types
only with the knowledge that these data type can operate and be performed on
without any idea of how they are implemented. So a user only needs to know what
a data type can do, but not how it will be implemented.
Data hiding: It is a technique especially practised in object-oriented
programming (OOP).Data hiding is hiding the details of internal data members
of an object.Data hiding is also known as Information hiding.

//program to explain data hiding


class Square {
private:
int Num;
public:
void Get() {
cout << "Enter Number:";
cin>>Num;
}
void Display() {
cout << "Square Is:" << Num*Num;
}
};

void main() {
Square Obj;
Obj.Get();
Obj.Display();
getch()
}

Output:
Square is : 25

In the above example, the variable “Num” is private. Hence this variable can be
accessed only by the members of the same class and is not accessible anywhere
else. Hence outside the classes will be unable to access this variable which is
called data hiding.
At the same time, “Square” class contains two other methods namely “Get” and
“Display” which has public members. Here “Get” method just prints the value
while “Display” method prints the square of the value in the variable “Num”.
Here the class “Square” implements Data Encapsulation concept by capsulation
of the value in the variable “Num” and thus allowing the user only to perform a
restricted set of operations on the hidden variable “Num”.

You might also like