C++Unit2 Complete Notes
C++Unit2 Complete Notes
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:
#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);
};
perc=(float)total/500*100;
}
int main()
{
student std; //object creation
std.getDetails();
std.putDetails();
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.
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
};
#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
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.
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;
class Numbers
{
private:
int a;
int b;
public:
Numbers()
{
a = 0;
b = 0;
}
//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:
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.
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.
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
#include <iostream>
using namespace std;
class Add{
public:
//Parameterized constructor
Add(int num1, int num2) {
cout<<(num1+num2)<<endl;
}
};
int main(void)
{
30
110
#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:
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);
// In Main Function
class_name object1(params);
void Display()
{
cout << "\nValues :" << a << "\t" << b;
}
};
int main() {
//Normal Constructor Invoked
Example Object(10, 20);
Output
Im Constructor
Im Copy Constructor
Im Copy Constructor
Values :10 20
Values :10 20
Values :10 20
Destructor in c++
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
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.
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.
public:
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.
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.
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”.