OOPs in C++
OOPs in C++
https://www.linkedin.com/in/himanshukumarmahuri
PART-2: -
➢ Object Oriented Programming in C++
➢ What is a class?
➢ What is an object?
➢ What is encapsulation?
➢ What is Polymorphism?
➢ What is Compile time Polymorphism and how is it different from Runtime
Polymorphism?
➢ How does C++ support Polymorphism?
➢ What is meant by Inheritance?
➢ What are the various types of inheritance?
➢ Why multiple inheritance is not supported in JAVA?
➢ What is Abstraction?
➢ How much memory does a class occupy?
➢ Is it always necessary to create objects from class in C++?
➢ What is a constructor?
➢ What are the various types of constructors in C++?
➢ What is a copy constructor?
➢ What is a destructor?
➢ Are class and structure the same? If not, what's the difference between a
class and a structure?
➢ Explain Inheritance with an example?
➢ What is a subclass?
➢ Define a superclass?
➢ What is the difference between overloading and overriding?
➢ What is an interface?
➢ What is meant by static polymorphism?
➢ What is meant by dynamic polymorphism?
Encapsulation in C++
In normal terms Encapsulation is defined as wrapping up of data and
information under a single unit. In Object Oriented Programming,
Encapsulation is defined as binding together the data and the functions that
manipulates them.
Consider a real life example of encapsulation, in a company there are different
sections like the accounts section, finance section, sales section etc. The finance
section handles all the financial transactions and keep records of all the data
related to finance. Similarly the sales section handles all the sales related
activities and keep records of all the sales. Now there may arise a situation
when for some reason an official from finance section needs all the data about
sales in a particular month. In this case, he is not allowed to directly access the
data of sales section. He will first have to contact some other officer in the sales
section and then request him to give the particular data. This is what
encapsulation is. Here the data of sales section and the employees that can
manipulate them are wrapped under a single name "sales section".
// Encapsulation
#include<iostream>
class Encapsulation
private:
int x;
public:
// variable x
void set(int a)
x =a;
// variable x
int get()
return x;
};
// main function
int main()
Encapsulation obj;
obj.set(5);
cout<<obj.get();
return 0; }
output:
In the above program the variable x is made private. This variable can be accessed
and manipulated only using the functions get () and set() which are present inside
the class. Thus we can say that here, the variable x and the functions get () and set()
are binded together which is nothing but encapsulation.
1. The data members should be labeled as private using the private access
specifiers
2. The member function which manipulates the data members should be
labeled as public using the public access specifier.
Polymorphism in C++
The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. A
real-life example of polymorphism, a person at the same time can have different
characteristics. Like a man at the same time is a father, a husband, an employee. So
the same person posses different behavior in different situations. This is called
polymorphism. Polymorphism is considered as one of the important features of
Object Oriented Programming.
#include <bits/stdc++.h>
class Geeks
public:
void func(int x)
}
// function with same name but 1 double parameter
void func(double x)
cout << "value of x and y is " << x << ", " << y << endl;
};
int main () {
DEMO obj1;
obj1.func(7);
obj1.func(9.132);
obj1.func(85,64);
return 0; }
Output:
value of x is 7
value of x is 9.132
value of x and y is 85, 64
In the above example, a single function named func acts differently in three
different situations which is the property of polymorphism.
Operater overloading:
C++ also provide option to overload operators. For example, we can make the
operator ('+') for string class to concatenate two strings. We know that this is the
addition operator whose task is to add two operands. So a single operator '+' when
placed between integer operands , adds them and when placed between string
operands, concatenates them.
// Operator Overloading
#include<iostream>
class Complex {
private:
public:
Complex res;
return res;
void print() { cout << real << " + i" << imag << endl; }
};
int main()
c3.print();
Output:
o 12 + i9
In the above example the operator '+' is overloaded. The operator '+' is an addition
operator and can add two numbers (integers or floating point) but here the operator
is made to perform addition of two imaginary or complex numbers.
Runtime polymorphism:
#include <bits/stdc++.h>
class base
public:
};
public:
void show ()
//main function
int main()
base *bptr;
derived d;
bptr = &d;
bptr->print();
bptr->show();
return 0;}
Output:
Abstraction in C++
Data abstraction is one of the most essential and important features of object
oriented programming in C++. Abstraction means displaying only essential
information and hiding the details. Data abstraction refers to providing only
essential information about the data to the outside world, hiding the background
details or implementation.
Consider a real-life example of a man driving a car. The man only knows that
pressing the accelerators will increase the speed of car or applying brakes will stop
the car but he does not know about how on pressing accelerator the speed is
actually increasing, he does not know about the inner mechanism of the car or the
implementation of accelerator, brakes etc in the car. This is what abstraction is.
Abstraction in Header files: One more type of abstraction in C++ can be header
files. For example, consider the pow() method present in math.h header file.
Whenever we need to calculate power of a number, we simply call the function
pow() present in the math.h header file and pass the numbers as arguments
without knowing the underlying algorithm according to which the function is
actually calculating power of numbers.
We can easily implement abstraction using the above two features provided by
access specifiers. Say, the members that defines the internal implementation can be
marked as private in a class. And the important information needed to be given to
the outside world can be marked as public. And these public members can access
the private members as they are inside the class.
Example:
#include <iostream>
class implementAbstraction
private:
int a, b;
public:
// private members
a = x;
b = y;
void display() {
};
int main()
{
implementAbstraction obj;
obj.set(10, 20);
obj.display();
return 0;
Output:
a = 10
b = 20
You 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.
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is
called Inheritance. Inheritance is one of the most important features of Object-
Oriented Programming.
• Sub Class: The class that inherits properties from another class is called Subclass or
Derived Class.
• Super Class: The class whose properties are inherited by a subclass is called Base
Class or Superclass.
You can clearly see that the above process results in duplication of the same code 3
times. This increases the chances of error and data redundancy. To avoid this type
of situation, inheritance is used. If we create a class Vehicle and write these three
functions in it and inherit the rest of the classes from the vehicle class, then we can
simply avoid the duplication of data and increase re-usability. Look at the below
diagram in which the three classes are inherited from vehicle class:
Using inheritance, we have to write the functions only one time instead of three
times as we have inherited the rest of the three classes from the base class
(Vehicle).
Implementing inheritance in C++: For creating a sub-class that is inherited from the
base class we have to follow the below syntax.
Syntax:
class subclass_name :
access_mode base_class_name
{// body of subclass
};
Here, subclass_name is the name of the subclass, access mode as the mode in which
you want to inherit the subclass for example public, private, etc.
and base_class_name is the name of the base class from which you want to inherit
the subclass.
Note: A derived class doesn't inherit access to private data members. However, it
does inherit a full parent object, which contains any private members which that class
declares.
class Parent {
public:
int id_p;
};
public:
int id_c;
};
// main function
int main()
Child obj1;
obj1.id_c = 7;
obj1.id_p = 91;
return 0;
}
Output:
Child id is: 7
Parent id is: 91
In the above program, the 'Child' class is publicly inherited from the 'Parent' class so the public data members of
the class 'Parent' will also be inherited by the class 'Child'.
1. Public Mode: If we derive a subclass from a public base class. Then the public member of the base class
will become public in the derived class and protected members of the base class will become protected
in the derived class.
2. Protected Mode: If we derive a subclass from a Protected base class. Then both public members and
protected members of the base class will become protected in the derived class.
3. Private Mode: If we derive a subclass from a Private base class. Then both public members and protected
members of the base class will become Private in the derived class.
Note: The private members in the base class cannot be directly accessed in the derived class, while protected
members can be directly accessed. For example, Classes B, C, and D all contain the variables x, y, and z in the
below example. It is just a question of access.
// C++ Implementation to show that a derived class
class A {
public:
int x;
protected:
int y;
private:
int z;
};
class B : public A {
// x is public
// y is protected
};
class C : protected A {
// x is protected
// y is protected
};
// x is private
// y is private
};
The below table summarizes the above three modes and shows the access specifier
of the members of the base class in the subclass when derived in public, protected
and private modes:
TYPES OF INHERITANCE IN C++:
1. Single Inheritance: In single inheritance, a class is allowed to inherit from only one
class. i.e. one subclass is inherited by one base class only.
Syntax:
// Single inheritance
#include<iostream>
// base class
class Vehicle {
public:
Vehicle()
};
};
// main function
int main()
Car obj;
return 0;
}
Output
This is a Vehicle
// multiple inheritance
#include <iostream>
class Vehicle {
public:
};
class FourWheeler {
public:
FourWheeler()
};
};
// main function
int main()
Car obj;
return 0;
Output
This is a Vehicle
This is a 4 wheeler Vehicle
// Multilevel Inheritance
#include <iostream>
// base class
class Vehicle {
public:
};
public:
fourWheeler()
};
public:
};
// main function
int main()
Car obj;
return 0;
Output
This is a Vehicle
Objects with 4 wheels are vehicles
Car has 4 Wheels
// Hierarchical Inheritance
#include <iostream>
// base class
class Vehicle {
public:
};
};
};
// main function
int main()
Car obj1;
Bus obj2;
return 0;
}
Output
This is a Vehicle
This is a Vehicle
#include <iostream>
// base class
class Vehicle {
public:
};
// base class
class Fare {
public:
};
};
};
// main function
int main()
Bus obj2;
return 0;
}
Output
This is a Vehicle
Fare of Vehicle
A derived class with two base classes and these two base classes have one common
base class is called multipath inheritance. Ambiguity can arise in this type of
inheritance.
// C++ program demonstrating ambiguity in Multipath
// Inheritance
#include <iostream>
class ClassA {
public:
int a;
};
public:
int b;
public:
int c;
};
public:
int d;
};
int main()
ClassD obj;
obj.c = 30;
obj.d = 40;
Output:
a from ClassB: 10
a from ClassC: 100
b : 20
c : 30
d : 40
In the above example, both ClassB and ClassC inherit ClassA, they both have a single
copy of ClassA. However, Class-D inherits both ClassB and ClassC, therefore Class-
D has two copies of Class A, one from ClassB and another from ClassC.
If we need to access the data member of ClassA through the object of Class-D, we
must specify the path from which a will be accessed, whether it is from ClassB or
ClassC, bcoz compiler can't differentiate between two copies of ClassA in Class-D.
#include<iostream>
class ClassA
public:
int a;
};
public:
int b;
};
public:
int c;
};
public:
int d;
};
int main()
ClassD obj;
obj.b = 20;
obj.c = 30;
obj.d = 40;
Output:
a : 100
b : 20
c : 30
d : 40
According to the above example, Class-D has only one copy of ClassA, therefore,
statement 4 will overwrite the value of a, given in statement 3.
Inline Functions in C++
Inline function is one of the important features of C++. So, let’s first understand why
inline functions are used and what is the purpose of inline function?
When the program executes the function call instruction the CPU stores the
memory address of the instruction following the function call, copies the arguments
of the function on the stack and finally transfers control to the specified function.
The CPU then executes the function code, stores the function return value in a
predefined memory location/register and returns control to the calling function. This
can become overhead if the execution time of function is less than the switching
time from the caller function to called function (callee). For functions that are large
and/or perform complex tasks, the overhead of the function call is usually
insignificant compared to the amount of time the function takes to run. However, for
small, commonly used functions, the time needed to make the function call is often
a lot more than the time needed to actually execute the function’s code. This
overhead occurs for small functions because execution time of small function is less
than the switching time.
C++ provides an inline function to reduce the function call overhead. Inline function
is a function that is expanded in line when it is called. When the inline function is
called whole code of the inline function gets inserted or substituted at the point of
inline function call. This substitution is performed by the C++ compiler at compile
time. Inline function may increase efficiency if it is small.
Remember, in lining is only a request to the compiler, not a command. Compiler can
ignore the request for in lining. Compiler may not perform inlining in such
circumstances like:
1)If a function contains a loop. (for, while, do-while)
3) If a function is recursive.
4) If a function return type is other than void, and the return statement doesn't exist
in function body.
5) If a function contains switch or goto statement.
2) It also saves the overhead of push/pop variables on the stack when function is
called.
4) When you inline a function, you may enable compiler to perform context specific
optimization on the body of function. Such optimizations are not possible for normal
function calls. Other optimizations can be obtained by considering the flows of calling
context and the called context.
5) Inline function may be useful (if it is small) for embedded systems because inline
can yield less code than the function call preamble and return.
2) If you use too many inline functions then the size of the binary
executable file will be large, because of the duplication of same code.
3) Too much inlining can also reduce your instruction cache hit rate, thus
reducing the speed of instruction fetch from that of cache memory to
that of primary memory.
4) Inline function may increase compile time overhead if someone
changes the code inside the inline function then all the calling location
has to be recompiled because compiler would require to replace all the
code once again to reflect the changes, otherwise it will continue with
old functionality.
Inline function and classes: It is also possible to define the inline function inside the class. In
fact, all the functions defined inside the class are implicitly inline. Thus, all the restrictions of
inline functions are also applied here. If you need to explicitly declare inline function in the
class then just declare the function inside the class and define it outside the class using inline
keyword.
For example:
class S
{
public:
inline int square(int s) // redundant use of inline
{
// this function is automatically inline
// function body
}
};
The above style is considered as a bad programming style. The best programming style is to
just write the prototype of function inside the class and specify it as an inline in the function
definition.
For example:
class S
public:
};
}
The following program demonstrates this concept:
#include <iostream>
class operation
int a,b,add,sub,mul;
float div;
public:
void get();
void sum();
void difference();
void product();
void division();
};
inline void operation :: get()
cin >> a;
cin >> b;
add = a+b;
cout << "Addition of two numbers: " << a+b << "\n";
sub = a-b;
cout << "Difference of two numbers: " << a-b << "\n";
mul = a*b;
cout << "Product of two numbers: " << a*b << "\n";
div=a/b;
int main()
s.get();
s.sum();
s.difference();
s.product();
s.division();
return 0;
Output:
Enter first value: 45
Enter second value: 15
Addition of two numbers: 60
Difference of two numbers: 30
Product of two numbers: 675
Division of two numbers: 3
What is wrong with macro? Readers familiar with the C language knows that C language
uses macro. The preprocessor replace all macro calls directly within the macro code. It is
recommended to always use inline function instead of macro. According to Dr. Bjarne
Stroustrup the creator of C++ that macros are almost never necessary in C++ and they are
error prone. There are some problems with the use of macros in C++. Macro cannot access
private members of class. Macros looks like function call but they are actually not.
Example:
#include <iostream>
class S
int m;
public:
C++ compiler checks the argument types of inline functions and necessary conversions are
performed correctly. Preprocessor macro is not capable for doing this. One other thing is
that the macros are managed by preprocessor and inline functions are managed by C++
compiler.
Remember: It is true that all the functions defined inside the class are implicitly inline and
C++ compiler will perform inline call of these functions, but C++ compiler cannot perform
inlining if the function is virtual. The reason is call to a virtual function is resolved at runtime
instead of compile time. Virtual means wait until runtime and inline means during
compilation, if the compiler doesn't know which function will be called, how it can perform
inlining?
One other thing to remember is that it is only useful to make the function inline if the time
spent during a function call is more compared to the function body execution time. An
example where inline function has no effect at all:
The above function relatively takes a long time to execute. In general function which
performs input output (I/O) operation shouldn't be defined as inline because it spends a
considerable amount of time. Technically inlining of show() function is of limited value
because the amount of time the I/O statement will take far exceeds the overhead of a
function call.
Depending upon the compiler you are using the compiler may show you warning if the
function is not expanded inline. Programming languages like Java & C# doesn't support
inline functions.
But in Java, the compiler can perform inlining when the small final method is called,
because final methods can’t be overridden by sub classes and call to a final method is
resolved at compile time. In C# JIT compiler can also optimize code by inlining small
function calls (like replacing body of a small function when it is called in a loop).
Last thing to keep in mind that inline functions are the valuable feature of C++. An
appropriate use of inline function can provide performance enhancement but if inline
functions are used arbitrarily then they can’t provide better result. In other words don’t
expect better performance of program. Don’t make every function inline. It is better to keep
inline functions as small as possible.
class Complex {
private:
public:
Complex res;
return res;
void print() { cout << real << " + i" << imag << '\n'; }
};
int main()
Complex c3 = c1 + c2;
c3.print();
Output:
12 + i9
class Complex {
private:
int real, imag;
public:
void print() { cout << real << " + i" << imag << '\n'; }
};
int main()
Complex c3 = c1 + c2;
c3.print();
return 0;
Output
12 + i9
. (dot)
::
?:
sizeof
Why can’t. (dot),::, ?: and size of be overloaded?
class Fraction
private:
public:
};
int main() {
float val = f;
return 0;
Output:
0.4
Overloaded conversion operators must be a member method. Other operators can
either be member method or global method.
4) Any constructor that can be called with a single argument works as a conversion
constructor, means it can also be used for implicit conversion to the class being
constructed.
#include <iostream>
class Point
private:
int x, y;
public:
Point(int i = 0, int j = 0) {
x = i; y = j;
void print() {
cout << "x = " << x << ", y = " << y << '\n';
};
int main() {
t.print();
t.print();
return 0;
Output:
x = 20, y = 20
x = 30, y = 0
Function Overloading in C++
#include <iostream>
using namespace std;
void print(int i) {
cout << " Here is int " << i << endl;
}
void print(double f) {
cout << " Here is float " << f << endl;
}
void print(char const *c) {
cout << " Here is char* " << c << endl;
}
int main() {
print(10);
print(10.10);
print("ten");
return 0;
}
Output:
Here is int 10
• If no match found:
• Copy Constructor
• Default assignment operator
// Copy Constructor
demo Obj1(Obj);
or
demo Obj1 = Obj;
• Depending upon the resources like dynamic memory held by the object,
either we need to perform Shallow Copy or Deep Copy in order to create a
replica of the object. In general, if the variables of an object have been
dynamically allocated then it is required to do a Deep Copy in order to create
a copy of the object
Shallow object
In shallow copy, an object is created by simply copying the data of all variables of the
original object. This works well if none of the variables of the object are defined in the heap
section of memory. If some variables are dynamically allocated memory from heap section,
then copied object variable will also reference then same memory location.
This will create ambiguity and run-time errors dangling pointer. Since both objects will
reference to the same memory location, then change made by one will reflect those change
in another object as well. Since we wanted to create a replica of the object, this purpose
will not be filled by Shallow copy.
Note: C++ compiler implicitly creates a copy constructor and overloads assignment
operator in order to perform shallow copy at compile time.
Shallow Copy of object if some variables are defined in heap memory, then:
Below is the implementation of the above approach:
#include <iostream>
// Box Class
class box {
private:
int length;
int breadth;
int height;
public:
int height1)
length = length1;
breadth = breadth1;
height = height1;
void show_data()
<< endl;
}};
// Driver Code
int main()
B1.show_data();
// COPY CONSTRUCTOR
box B2 = B1;
B2.show_data();
// ASSIGNMENT OPERATOR
B3 = B1;
B3.show_data();
return 0;
Output:
Length = 14
Breadth = 12
Height = 16
Length = 14
Breadth = 12
Height = 16
Length = 14
Breadth = 12
Height = 16
Deep Copy:
In Deep copy, an object is created by copying data of all variables and it also
allocates similar memory resources with the same value to the object. In order to
perform Deep copy, we need to explicitly define the copy constructor and assign
dynamic memory as well if required. Also, it is required to dynamically allocate
memory to the variables in the other constructors, as well.
Below is the implementation of the above approach:
// deep copy
#include <iostream>
// Box Class
class box {
private:
int length;
int* breadth;
int height;
public:
// Constructor
box()
// of the Box
int heig)
length = len;
*breadth = brea;
height = heig;
// of the Box
void show_data()
<< endl;
length = sample.length;
*breadth = *(sample.breadth);
height = sample.height;
// Destructors
~box()
delete breadth;
};
// Driver Code
int main()
box first;
first.show_data();
second.show_data();
return 0;
Output:
Length = 12
Breadth = 14
Height = 16
Length = 12
Breadth = 14
Height = 16
HIMANSHU KUMAR(LINKEDIN)
https://www.linkedin.com/in/himanshukumarmahuri
CREDITS- INTERNET.
DISCLOSURE- ALL THE DATA AND IMAGES ARE TAKEN FROM GOOGLE AND INTERNET.
REFRENCES USED-
2) http://www.parashift.com/c++-faq/inline-and-perf.html
3) http://www.cplusplus.com/forum/articles/20600/
6) http://en.wikipedia.org/wiki/Operator_overloading
FOLLOW ME FOR PART-2 OF THIS NOTES AND ALSO FOR MORE AMAZING INFORMATIVE NOTES AND
CONTENS.
THANKYOU