C++ UNIT 1&2
C++ UNIT 1&2
Object means a real word entity such as pen, chair, table etc. 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:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
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.
Class
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.
Polymorphism
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.
Encapsulation is typically understood as the grouping of related pieces of
information and data into a single entity. Encapsulation is the process of tying
together data and the functions that work with it in object-oriented
programming.
Declaring Objects: When a 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, you need to create objects. Syntax:
ClassName ObjectName;
o #include <iostream>
o class Student
o {
o public:
o int id;//data member (also instance variable)
o string name;//data member(also instance variable)
o };
o int main()
o {
o Student s1; //creating an object of Student
o s1.id = 201;
o s1.name = "Esther";
o cout<<s1.id<<endl;
o cout<<s1.name<<endl;
o return 0;
o }
A member function of a class is a function that has its definition or its prototype
within the class definition like any other variable. It operates on any object of
the class of which it is a member, and has access to all the members of a class
for that object.
Let us take previously defined class to access the members of the class using a
member function instead of directly accessing them −
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
double getVolume(void);// Returns box volume
};
Member functions can be defined within the class definition or separately
using scope resolution operator, : −. Defining a member function within the
class definition declares the function inline, even if you do not use the inline
specifier. So either you can define Volume() function as below −
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
double getVolume(void) {
return length * breadth * height;
}
};
If you like, you can define the same function outside the class using the scope
resolution operator (::) as follows −
double Box::getVolume(void) {
return length * breadth * height;
}
Here, only important point is that you would have to use class name just before
:: operator. A member function will be called using a dot operator (.) on a object
where it will manipulate data related to that object only as follows −
Box myBox; // Create an object
C++ inline function is powerful concept that is commonly used with classes. If
a function is inline, the compiler places a copy of the code of that function at
each point where the function is called at compile time.
Any change to an inline function could require all clients of the function to be
recompiled because compiler would need to replace all the code once again
otherwise it will continue with old functionality.
To inline a function, place the keyword inline before the function name and
define the function before any calls are made to the function. The compiler can
ignore the inline qualifier in case defined function is more than a line.
A function definition in a class definition is an inline function definition, even
without the use of the inline specifier.
#include<iostream>
class Circle
private:
double radius;
public:
void compute_area(double r)
radius = r;
};
int main()
Circle obj;
obj.compute_area(1.5);
return 0;
Output:
Radius is: 1.5
Area is: 7.065
Syntax
1. static data_type data_member;
The data_type is the variable type in C++, such as int, float, string, etc.
Syntax
1. class_name::function_name (parameter);
function_name: The function name is the name of the static member function.
parameter: It defines the name of the pass arguments to the static member
function.
Example
o #include <iostream>
o class Note
o {
o // declare a static data member
o static int num;
o
o public:
o // create static member function
o static int func ()
o {
o return num;
o }
o };
o // initialize the static data member using the class name and the scope res
olution operator
o int Note :: num = 5;
o
o int main ()
o {
o // access static member function using the class name and the scope resol
ution
o cout << " The value of the num is: " << Note:: func () << endl;
o return 0;
o }
Output
This is useful, when we want to initialize all data members of an object with
another object, we can pass objects and assign the values of supplied object to
the current object. For complex or large projects, we need to use objects as an
argument or parameter.
Example:
#include <iostream>
class Demo {
private:
int a;
public:
void set(int x)
{
a = x;
}
void print()
{
cout << "Value of A : " << a << endl;
}
};
int main()
{
//object declarations
Demo d1;
Demo d2;
Demo d3;
return 0;
}
Output
Value of A : 10
Value of A : 20
Value of A : 30
Arrays of objects
Like array of other user-defined data types, an array of type class can also
be created.
The array of type class contains the objects of the class as its individual
elements.
Thus, an array of a class type is also known as an array of objects.
An array of objects is declared in the same way as an array of any built-in
data type.
Syntax:
Example:
#include <iostream>
class MyClass {
int x;
public:
void setX(int i) { x = i; }
int getX() { return x; }
};
void main()
{
MyClass obs[4];
int i;
getch();
}
Output:
obs[0].getX(): 0
obs[1].getX(): 1
obs[2].getX(): 2
obs[3].getX(): 3
Friend function
If a function is defined as a friend function in C++, then the protected and
private data of a class can be accessed using the function.
By using the keyword friend compiler knows the given function is a friend
function.
For accessing the data, the declaration of a friend function should be done inside
the body of a class starting with the keyword friend.
1. class class_name
2. {
3. friend data_type function_name(argument/s); // syntax of friend functi
on.
4. };
In the above declaration, the friend function is preceded by the keyword friend.
The function can be defined anywhere in the program like a normal C++
function. The function definition does not use either the keyword friend or
scope resolution operator.
#include <iostream>
class Box
{
private:
int length;
public:
Box(): length(0) { }
friend int printLength(Box); //friend function
};
int printLength(Box b)
{
b.length += 10;
return b.length;
}
int main()
{
Box b;
cout<<"Length of box: "<< printLength(b)<<endl;
return 0;
}
Output:
Length of box: 10
UNIT 2
CONSTRUCTORS AND DESTRUCTORS
Constructors
Constructors are functions of a class that are executed when new objects of the
class are created. The constructors have the same name as the class and no
return type, not even void. They are primarily useful for providing initial values
for variables of the class.
Characteristics of Constructor
A constructor is a special member function of the class. It is different from a
generic member function for the following reasons:
Constructor member is scoped public
It has the same name as that of declaring class.
The name is case-sensitive
Constructors do not have a return type.
The default constructor is implicitly created.
When creating an object, the constructor gets called automatically.
A constructor is not implicitly inherited.
It usually has different rules for scope modifiers.
The two main types of constructors are default constructors and parameterized
constructors.
Default Constructors
Output
num1 = 5
num2 = 7
Parameterized Constructors
The parameterized constructors can take arguments to initialize an object when
it is created. Parameters are added to a parameterized constructor just like they
are added to a normal function. The parameterized constructors can be called
implicitly or explicitly.
A program that demonstrates parameterized constructors is given as follows.
Example
#include <iostream>
class A
{
private:
int num1, num2 ;
public:
A(int n1, int n2)
{
num1 = n1;
num2 = n2;
}
void display()
{
cout<<"num1 = "<< num1 <<endl;
cout<<"num2 = "<< num2 <<endl;
}
};
int main()
{
A obj(3,8);
obj.display();
return 0;
}
Output
num1 = 3
num2 = 8
main()
{
Rect r1;
Rect r2(2, 6);
r1.display();
r2.display();
}
Output
The area is: 0
The area is: 12
#include<iostream>
class Simple
int data1;
int data2;
int data3;
public:
data1 = a;
data2 = b;
data3 = c;
void printData();
};
{
cout<<"The value of data1, data2 and data3 is "<<data1<<", "<< data2<<"
and "<< data3<<endl;
int main()
s.printData();
return 0;
Copy Constructor
In the above case, copy constructor can be called in the following ways:
#include <iostream>
class A
{
public:
int x;
A(int a) // parameterized constructor.
{
x=a;
}
A(A &i) // copy constructor
{
x = i.x;
}
};
int main()
{
A a1(20); // Calling the parameterized constructor.
A a2(a1); // Calling the copy constructor.
cout<<a2.x;
return 0;
}
Output:
20
Dynamic Constructor
When you use dynamic memory allocator new inside the constructor to create
dynamic memory, it is called dynamic constructor.
1. The dynamic constructor does not create the memory of the object but it
creates the memory block that is accessed by the object.
2. You can also gives arguments in the dynamic constructor you want to
declared as shown in Example 2.
Example
#include<iostream>
class Mania
// default constructor
Mania()
void display()
};
int main()
Mania obj1;
obj1.display();
Output:
Learning Mania
Const Objects
we declare the object as constant using the const keyword in our C++
program.
By doing this, the properties of the object once initialized cannot be changed
further.If an attempt is made to change the value of any attribute of
the const object, the compiler will throw the error.
cout << dog.name << " is of " << dog.breed << endl;
}
If we now try to change the value of breed, the compiler will throw an error.
Destructor
Destructor is an instance member function which is invoked automatically
whenever an object is going to be destroyed. Meaning, a destructor is the last
function that is going to be called before an object is destroyed.
#include <iostream>
class Employee
{
public:
Employee()
{
cout<<"Constructor Invoked"<<endl;
}
~Employee()
{
cout<<"Destructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
return 0;
}
Output:
Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked