OOP Cheatsheet
OOP Cheatsheet
C++ Class
Class is a user defined data type that have its own
properties and behaviors.
In C++, class is a group of similar objects. It is a
template from which objects are created. It can have
fields, methods, constructors etc.
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.
An object is an instance of a Class. It is an
identifiable entity with some characteristics and
behavior. Objects are the basic units of object-
oriented programming. It may be any real-world
object like a person, chair, table, pen, animal, car, etc.
A simple example of an object would be a car.
Logically, you would expect a car to have a model
number or name. This would be considered the
property of the car. You could also expect a car to be
able to do something, such as starting or moving.
This would be considered a method or properties of
the car.
Features of OOPs:
Four major object-oriented programming features
make them different from non-OOP languages:
Objects:
An object is an instance of the class.
Memory is allocated as soon as an object is created.
An object is a real-world entity such as a book, car,
etc.
An object is a physical entity.
Objects can be created many times as per
requirement.
Objects of the class car can be BMW, Mercedes,
Ferrari, etc.
C++ Constructor
A constructor is a special member function
automatically called when an object is created. In
C++, the constructor is automatically called when an
object is created. It is a special class method
because it does not have any return type. It has the
same name as the class itself. It is used to initialize
the data members of new object generally.
referred.
Constructor make implicit calls
Default constructor:
A constructor that doesn't take any argument or has
no parameters is known as a default constructor.
Ex:
Student s;
Will flash an error
Parameterized Constructor:
This is another type of Constructor with
parameters. The parameterized constructor takes
its arguments provided by the programmer. These
arguments help initialize an object when it is
created.
Using this Constructor, you can provide different
values to data members of different objects by
passing the appropriate values as arguments.
Copy Constructor:
These are a particular type of constructor that takes
an object as an argument and copies values of one
object’s data members into another object. We
pass the class object into another object of the
same class in this constructor. As the name
suggests, you Copy means to copy the values of one
Object into another Object of Class. This is used for
Copying the values of a class object into another
object of a class, so we call them Copy constructor
and for copying the values.
Syntax:
Class class_name{
intdata_member1;
stringdata_member2;
//copy constructor
public:
class_name(class_name &obj){
// copies data of the obj parameter
data_member1 = obj.data_member1;
data_member2 = obj.data_member2;
}
};
Constructor Overloading:
Constructor overloading can be defined as the
concept of having more than one constructor with
different parameters so that every constructor can
perform a different task.
As there is a concept of function overloading,
similarly constructor overloading is applied when
we overload a constructor more than a purpose.
The declaration is the same as the class name, but
there is no return type as they are constructors.
The criteria to overload a constructor is to differ the
number of arguments or the type of arguments. The
corresponding constructor is called depending on
the number and type of arguments passed.
Destructor:
A destructor is a special member function that
works just opposite to a constructor;
Unlike constructors that are used for initializing an
object, destructors destroy (or delete) the object.
The purpose of the destructor is to free the
resources that the object may have acquired during
its lifetime.
~class_name() {
}
The destructor name should exactly match the class
name. A destructor declaration should always begin
with the tilde (~) symbol, as shown in the syntax
above.
Destructor rules
❖ The name should begin with a tilde sign (~) and
match the class name.
❖ There cannot be more than one destructor in a
class.
❖ Unlike constructors that can have parameters,
destructors do not allow any parameter.
❖ They do not have any return type, not even void.
❖ A destructor should be declared in the public
section of the class.
❖ The programmer cannot access the address of
the destructor.
❖ When you do not specify any destructor in a
class, the compiler generates a default destructor
and inserts it into your code.
❖ It cannot be declared static or const.
class Test {
private:
~Test() {}
};
int main() {}
The above program compiles and runs fine.
Hence, we can say that: It is not a compiler
error to create private destructors.
class Test {
private:
~Test() {}
};
int main() { Test t; }
for this compiler gives an error.
class Test {
private:
~Test() {}
};
int main() { Test* t; }
The above program works fine. There is
no object being constructed, the
program just creates a pointer of type
“Test *”, so nothing is destructed.
class Test {
private:
~Test() {}
};
int main() { Test* t = new Test; }
The above program also works fine.
When something is created using
dynamic memory allocation, it is the
programmer’s responsibility to delete it.
So, compiler doesn’t bother.
In the case where the destructor is
declared private, an instance of the class
can also be created using the malloc ()
function. The same is implemented in
the below program.
Program fails in the compilation. When
we call delete, destructor is called.
class parent {
// private destructor
~parent() { cout << "destructor
called" << endl; }
public:
parent() { cout << "constructor
called" << endl; }
void destruct() { delete this; }
};
int main()
{
parent* p;
p = new parent;
// destructor called
p->destruct();
return 0;
}
Interview Questions
1. Does C++ compiler create a default
constructor when we write our own?
Ans: In C++, compiler by default creates a
default constructor for every class. But, if
we define our own constructor, compiler
does not create the default constructor.
this Pointer
this pointer holds the address of the current object.
in simple words, you can say that this pointer points
to the current object of the class.
There can be three main usages of this keyword in
C++.
●It can be used to refer to a current class
instance variable.
●It can be used to pass the current object as a
parameter to another method.
●It can be used to declare indexers.
Int main () {
mobile redmi;
redmi.set_details("Note 7 Pro",2019);
redmi.print();
}
Output: 1Note 7 Pro 2019 Here you can see
that we have two data members model and
year_of_manufacture. In member function
set_details (), we have two local variables with
the same name as the data members’ names.
Suppose you want to assign the local variable
value to the data members. In that case, you
won’t be able to do until unless you use this
pointer because the compiler won’t know that
you are referring to the object’s data members
unless you use this pointer. This is one of
example where you must use this pointer.
Explain the situation where this pointer is used:
As we know each object gets its own copy of data
members and all objects shares a single copy of
member functions.
Then now, question is that if only one copy of each
member function exist which is used by multiple
objects, how are the proper data members are
accessed and updated.
Ans: The complier supplies an implicit pointer
along with the names of the functions as “this”.
Where “this” refers the address of current.
The ‘this’ pointer is available only within the non-
static member functions of a class. If the member
function is static, it will be common to all the
objects, and hence a single object can’t refer to
those functions independently.
Static data member and member functions in
C++:
Static members are class member that are declared
using ‘Static’ key word.
A static member has certain special characteristic’s
Only one copy of that member is created for the
entire class and that copy is shared by all the
objects of that class. No matter how many objects
are created.
It is initialized before any object of this class is
being created, even before main starts.
It is visible only within the class, but its lifetime is
in the entire program.
static data_type name_of_member;
Declared inside the class body.
Defined outside the class.
Static member variables are not belonging to any
objects, but its belongs to whole class so these
are called class member variable.
Advantage of C++ static keyword:
Memory efficient: Now we do not need to create
instance for accessing the static members, so it
saves memory. Moreover, it belongs to the type, so
it will not get memory each time when instance is
created.
Truck () {
Count++;
}
};
Shallow Copy:
An object is created by simply copying the data of
all variables of the original object. Here, the pointer
will be copied but not the memory it points to.
It means that the original object and the created
copy will now point to the same memory address,
which is generally not preferred.
Since both objects will reference the exact memory
location, then change made by one will reflect
those change in another object as well.
This can lead to unpleasant side effects if the
elements of values are changed via some other
reference.
Since we wanted to create an object replica, the
Shallow copy will not fulfill this purpose.
Shallow Copy
Shallow Copy stores the references of objects to
the original memory address.
Shallow Copy reflects changes made to the
new/copied object in the original object.
Shallow Copy stores the copy of the original
object and points the references to the objects.
Shallow copy is faster.
Deep Copy
Deep copy stores copies of the object’s value.
Deep copy doesn’t reflect changes made to the
new/copied object in the original object.
Deep copy stores the copy of the original object
and recursively copies the objects as well.
Deep copy is comparatively slower.
Access Modifiers in Java:
Link => https://www.geeksforgeeks.org/access-
modifiers-java/
Default: When no access modifier is specified for
a class, method, or data member – It is said to be
having the default access modifier by default.
The data members, classes, or methods that are
not declared using any access modifiers i.e.,
having default access modifier are accessible only
within the same package.
class X
{
public:
static void f()
{
// statement
}
};
int main()
{
X::f(); // calling member function
directly with class name
}
It doesn't have any "this" keyword which is the reason it cannot access
ordinary members.
When used with member function, such member functions can never
modify the object or its related data members.
basic syntax of const Member Function
// statement
For example:
class WithFriend {
int i;
public:
WithFriend wf;
int main(){
class Other{
void fun();
};
class WithFriend{
private:
int i;
public:
};
#include<iostream>
using namespace std;
class base {
public:
virtual void print()
{
cout << "print base class\n";
}
void show()
{
cout << "show base class\n";
}
};
void show()
{
cout << "show derived class\n";
}
};
int main()
{
base *bptr;
derived d;
bptr = &d;
return 0;
}
Output:
print derived class
show base class
NOTE: 1. Runtime polymorphism is
achieved only through a pointer (or
reference) of base class type. Also, a base
class pointer can point to the objects of
base class as well as to the objects of
derived class. In above code, base class
pointer ‘bptr’ contains the address of object
‘d’ of derived class.
2. Late binding (Runtime) is done in
accordance with the content of pointer (i.e.
location pointed to by pointer) and Early
binding (Compile time) is done according to
the type of pointer.
3. since print () function is declared with
virtual keyword so it will be bound at
runtime (output is print derived class as
pointer is pointing to object of derived
class) and show () is non-virtual so it will be
bound during compile time (output is show
base class as pointer is of base type).
4. If we have created a virtual function in
the base class and it is being overridden in
the derived class then we do not need
virtual keyword in the derived class,
functions are automatically considered as
virtual functions in the derived class.
> Working of virtual functions (concept of
VTABLE and VPTR)
class base {
public:
void fun_1() { cout << "base-1\n"; }
virtual void fun_2() { cout << "base-2\n"; }
virtual void fun_3() { cout << "base-3\n"; }
virtual void fun_4() { cout << "base-4\n"; }
};
int main()
{
base *p;
derived obj1;
p = &obj1;
return 0;
}
Output:
base-1
derived-2
base-3
base-4
// Base class
class Shape {
public:
// parameterized constructor
Shape(int l, int w)
{
length = l;
width = w;
}
int get_Area()
{
cout << "This is call to parent class area\n";
// Returning 1 in user-defined function means
true
return 1;
}
protected:
int length, width;
};
// Derived class
class Square : public Shape {
public:
Square(int l = 0, int w = 0)
: Shape(l, w)
{
} // declaring and initializing derived class
// constructor
int get_Area()
{
cout << "Square area: " << length * width <<
'\n';
return (length * width);
}
};
// Derived class
class Rectangle : public Shape {
public:
Rectangle(int l = 0, int w = 0)
: Shape(l, w)
{
} // declaring and initializing derived class
// constructor
int get_Area()
{
cout << "Rectangle area: " << length * width
<< '\n';
return (length * width);
}
};
int main()
{
Shape* s;
===========================================
To resolve this problem, we must use virtual function
// C++ program to demonstrate how we will calculate
// the area of shapes USING VIRTUAL FUNCTION
#include <fstream>
#include <iostream>
using namespace std;
void calculate()
{
cout << "Enter Width of Rectangle: ";
cin >> width;
void calculate()
{
cout << "Enter one side your of Square: ";
cin >> side;
int main()
{
class Employee {
public:
virtual void raiseSalary()
{
// common raise salary code
}
Virtual Destructor
We cannot delete a derived class object using a
base class pointer that has a non-virtual
destructor. To delete the derived class object
using the base class pointer, the base class must
contain a virtual destructor. It will be clearer as
we understand the following examples.
Deleting a derived class object using a pointer
of base class type that has a non-virtual
destructor result in undefined behavior. To
correct this situation, the base class should be
defined with a virtual destructor. For
example, following program results in
undefined behavior.
#include<iostream>
using namespace std;
class Base
{
public:
virtual void show() { cout<<" In Base \n"; }
};
int main(void)
{
Base *bp = new Derived;
bp->show();
return 0;
}
(A)
In Base
In Base
(B)
In Base
In Derived
(C)
In Derived
In Derived
(D)
In Derived
In Base
Answer: (C)
class Base
{
public:
virtual void show() { cout<<" In Base \n"; }
};
int main(void)
{
Base *bp, b;
Derived d;
bp = &d;
bp->show();
bp = &b;
bp->show();
return 0;
}
(A)
In Base
In Base
(B)
In Base
In Derived
(C)
In Derived
In Derived
(D)
In Derived
In Base
Answer: (D)
Answer: (C)
#include<iostream>
using namespace std;
class Base
{
public:
virtual void show() = 0;
};
int main(void)
{
Base b;
Base *bp;
return 0;
}
(A) There are compiler errors in lines “Base b;” and “Base
bp;”
(B) There is compiler error in line “Base b;”
(C) There is compiler error in line “Base bp;”
(D) No compiler Error
Answer: (B)
#include<iostream>
using namespace std;
class Base
{
public:
virtual void show() = 0;
};
int main(void)
{
Derived q;
return 0;
}
(A) Compiler Error: there cannot be an empty derived
class
(B) Compiler Error: Derived is abstract
(C) No compiler Error
Answer: (B)
#include<iostream>
using namespace std;
class Base
{
public:
virtual void show() = 0;
};
class Derived: public Base
{
public:
void show() { cout<<"In Derived \n"; }
};
int main(void)
{
Derived d;
Base &br = d;
br.show();
return 0;
}
(A) Compiler Error in line “Base &br = d;”
(B) Empty Output
(C) In Derived
Answer: (C)
C++ | Virtual Functions | Question 9
#include <iostream>
using namespace std;
class Base {
public:
virtual ~Base() {}
};
int main() {
return 0;
}
(A) Yes
(B) No
Answer: (A)
Explanation: A destructor can be virtual. We may want
to call appropriate destructor when a base class pointer
points to a derived class object and we delete the object.
If destructor is not virtual, then only the base class
destructor may be called.
#include<iostream>
using namespace std;
class Base {
public:
Base() { cout<<"Constructor: Base"<<endl; }
virtual ~Base() { cout<<"Destructor : Base"<<endl; }
};
class Derived: public Base {
public:
Derived() { cout<<"Constructor: Derived"<<endl; }
~Derived() { cout<<"Destructor : Derived"<<endl; }
};
int main() {
Base *Var = new Derived();
delete Var;
return 0;
}
(A)
Constructor: Base
Constructor: Derived
Destructor : Derived
Destructor : Base
(B)
Constructor: Base
Constructor: Derived
Destructor : Base
(C)
Constructor: Base
Constructor: Derived
Destructor : Derived
(D)
Constructor: Derived
Destructor : Derived
Answer: (A)
class Test
{
public:
virtual static void fun() { }
};
(A) Yes
(B) No
Answer: (B)
#include <iostream>
using namespace std;
class A
{
public:
virtual void fun();
};
class B
{
public:
void fun();
};
int main()
{
int a = sizeof(A), b = sizeof(B);
if (a == b) cout << "a == b";
else if (a > b) cout << "a > b";
else cout << "a < b";
return 0;
}
(A) a > b
(B) a == b
(C) a < b
(D) Compiler Error
Answer: (A)
class A
{
public:
virtual void fun() { cout << "A::fun() "; }
};
class B: public A
{
public:
void fun() { cout << "B::fun() "; }
};
class C: public B
{
public:
void fun() { cout << "C::fun() "; }
};
int main()
{
B *bp = new C;
bp->fun();
return 0;
}
(A) A::fun()
(B) B::fun()
(C) C::fun()
Answer: (C)
#include<iostream>
using namespace std;
class Base
{
public:
virtual void show() { cout<<" In Base \n"; }
};
int main(void)
{
Base *bp = new Derived;
bp->Base::show(); // Note the use of scope
resolution here
return 0;
}
(A) In Base
(B) In Derived
(C) Compiler Error
(D) Runtime Error
Answer: (A)
#include <iostream>
int main()
{
// Calling of derived member function
Base* b = new Derived();
delete b;
return 0;
}
Output
~Derived () is executed
Pure virtual destructor is called
#include <iostream>
class Test {
public:
virtual ~Test() = 0;
// Test now becomes abstract class
};
Test::~Test() {}
// Driver Code
int main()
{
Test p;
Test* t1 = new Test;
return 0;
}
https://www.tutorialspoint.com/virtual-copy-
constructor-in-cplusplus
read this brother.
Example
public abstract class Employee {
private String name;
private String address;
private int number;
public:
// Parameterized constructor
Complex(double r = 0.0,
double i = 0.0) : real(r),
imag(i)
{
}
// Driver Code
int main()
{
// a Complex object
Complex com1(3.0, 0.0);
if (com1 == 3.0)
cout << "Same";
else
cout << "Not Same";
return 0;
}
Output
Same
class Complex {
private:
double real;
double imag;
public:
// Default constructor
explicit Complex(double r = 0.0,
double i = 0.0) :
real(r), imag(i)
{
}
// Driver Code
int main()
{
// a Complex object
Complex com1(3.0, 0.0);
if (com1 == 3.0)
cout << "Same";
else
cout << "Not Same";
return 0;
}
class Complex {
private:
double real;
double imag;
public:
// Default constructor
explicit Complex(double r = 0.0,
double i = 0.0):
real(r) , imag(i)
{
}
// Driver Code
int main()
{
// a Complex object
Complex com1(3.0, 0.0);
if (com1 == (Complex)3.0)
cout << "Same";
else
cout << "Not Same";
return 0;
}
Output
Same
Note: The explicit specifier can be used with a
constant expression. However, if that constant
expression evaluates to true, then only the function
is explicit.
Note: The explicit specifier can be used with a constant expression.
However, if that constant expression evaluates to true, then only the
function is explicit.
program.
Explicit value needed to be provided to the
Encapsulation:
Encapsulation is process of binding the code
and data into a single unit. whenever we need
to restrict the data from outside of class
people then we can make our data members
as private.
Encapsulation refers to bundling data and the
methods that operate on that data into a single
unit. Many programming languages use
encapsulation frequently in the form of classes. A
class is an example of encapsulation in computer
science in that it consists of data and methods that
have been bundled into a single unit.
classStudent{
private:
string studentName;
int studentRollno;
int studentAge;
public:
string getStudentName() {
return studentName;
}
Int getStudentAge() {
returnstudentAge;
}
Output:
Student Name : Avinash
Student Rollno : 101
Student Age : 22
How can Encapsulation be achieved?
Ans: Using access modifier.
Advantage of Encapsulation
By providing only a setter or getter method, you
can make the class read-only or write-only. In
other words, you can skip the getter or setter
methods.
It provides you the control over the data.
Suppose you want to set the value of id which
should be greater than 100 only, you can write
the logic inside the setter method. You can write
the logic not to store the negative numbers in the
setter methods.
It is a way to achieve data hiding in Java because
other class will not be able to access the data
through the private data members.
The encapsulate class is easy to test. So, it is
better for unit testing.
Abstraction: Implementation
hiding
An abstraction is a way of hiding the
implementation details and showing only the
functionality to the users. In other words, it
ignores the irrelevant details and shows only the
required one.
Because the user is not interested to know the
implementation.
It is also safe from the security point of view.
Using Interface
In Java, an interface is similar to Java classes. The difference is only
that an interface contains empty methods (methods that do not
have method implementation) and variables. In other words, it is a
collection of abstract methods (the method that does not have a
method body) and static constants. The important point about an
interface is that each method is public and abstract and does not
contain any constructor. Along with the abstraction, it also helps to
achieve multiple inheritance. The implementation of these methods
provided by the clients when they implement the interface.
Note: Using interface, we can achieve 100% abstraction.
Features of Interface:
Syntax:
Car.java
1. interface CarStart
2. {
3. void start();
4. }
5. interface CarStop
6. {
7. void stop();
8. }
9. public class Car implements CarStart, CarStop
10. {
11. public void start()
12. {
13. System.out.println("The car engine has been started.");
14. }
15. public void stop()
16. {
17. System.out.println("The car engine has been stopped.");
18. }
19. public static void main(String args[])
20. {
21. Car c = new Car();
22. c.start();
23. c.stop();
24. }
25. }
Output:
The car engine has been started.
The car engine has been stopped.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Abstraction is hiding complex code.
Simply, abstract class achieves partial
abstraction (0 to 100%) whereas interface
achieves fully abstraction (100%).
Inheritance:
Inheritance in Java is a mechanism in which one
object acquires all the properties and behaviors of a
parent object.
The idea behind inheritance in Java is that you can
create new classes that are built upon existing
classes. When you inherit from an existing class, you
can reuse methods and fields of the parent class.
Moreover, you can add new methods and fields in
your current class also.
Terms used in Inheritance
o Class: A class is a group of objects which have common
properties. It is a template or blueprint from which
objects are created.
o Sub Class/Child Class: Subclass is a class which
inherits the other class. It is also called a derived class,
extended class, or child class.
o Super Class/Parent Class: Superclass is the class from
where a subclass inherits the features. It is also called a
base class or a parent class.
o Reusability: As the name specifies, reusability is a
mechanism which facilitates you to reuse the fields and
methods of the existing class when you create a new
class. You can use the same fields and methods already
defined in the previous class.
Modes of Inheritance
1. Public mode: If we derive a subclass from a
public base class. Then, the base class’s public
members will become public in the derived
class, and protected class members 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.
o Type Conversion.
o Function with default arguments.
o Function with pass by reference.
o Type Conversion:
#include<iostream>
using namespace std;
void fun(int);
void fun(float);
void fun(int i)
{
std::cout << "Value of i is : " <<i<< std::endl;
}
void fun(float j)
{
std::cout << "Value of j is : " <<j<< std::endl;
}
int main()
{
fun(12);
fun(1.2);
return 0;
}
#include<iostream>
using namespace std;
void fun(int);
void fun(int,int);
void fun(int i)
{
std::cout << "Value of i is : " <<i<< std::endl;
}
void fun(int a,int b=9)
{
std::cout << "Value of a is : " <<a<< std::endl;
}
int main()
{
fun(12);
return 0;
}
Complexoperator+ (Complexconst& b) {
Complex a;
a.real = real + b.real;
a.imag = imag + b.imag;
returna;
}
voidprint() {
cout<< real <<" + i"<< imag <<endl;
}
};
intmain() {
Complexc1(10,5),c2(2,4);
Complex c3 = c1 + c2;
// An example call to "operator+"
c3.print();
}
Output: 12+ i9
❖Runtime polymorphism:
Runtime polymorphism is also known as dynamic
polymorphism. Method overriding is a way to
implement runtime polymorphism.
Runtime polymorphism or Dynamic Method
Dispatch is a process in which a call to an
overridden method is resolved at runtime rather
than compile-time.
Method overriding: Method overriding is a
feature that allows you to redefine the parent
class method in the child class based on its
requirement. In other words, whatever methods
the parent class has by default are available in the
child class. But, sometimes, a child class may not
be satisfied with parent class method
implementation. The child class is allowed to
redefine that method based on its requirement.
This process is called method overriding.
Example:
#include<iostream>
usingnamespacestd;
classParent{
public:
void show() {
cout<<"Inside parent class"<<endl;
}
};
classsubclass1:publicParent {
public:
void show() {
cout<<"Inside subclass1"<<endl;
}
};
classsubclass2:publicParent {
public:
void show() {
cout<<"Inside subclass2";
}
};
Int main() {
subclass1 o1;
subclass2 o2;
o1.show();
o2.show();
}
Output:
Inside subclass1
Inside subclass2
Interview Questions:
1. What is Encapsulation in C++? Why is it called
Data hiding?
=> The process of binding data and corresponding
methods (behavior) into a single unit is called
encapsulation in C++. In other words,
encapsulation is a programming technique that
binds the class members (variables and methods)
together and prevents them from accessing other
classes. Thereby we can keep variables and
methods safes from outside interference and
misuse. If a field is declared private in the class, it
cannot be accessed by anyone outside the class
and hides the fields. Therefore, Encapsulation is
also called data hiding.
class A {
public:
int a;
A(){
a = 10;
}
};
class base {
public:
base() {
std::cout << "base class constructor\n";
}
virtual ~base(){
std::cout << "base class destructor\n";
}
void show(){
std::cout << "show() called on base class\n";
}
virtual void print(){
std::cout << "print() called on base class\n";
}
};
virtual ~derived(){
std::cout << "derived class destructor\n";
}
private:
virtual void print(){
std::cout << "print() called on derived
class\n";
}
};
int main(){
std::cout << "printing with base class pointer\n";
Output
printing with base class pointer
base class constructor
derived class constructor
show() called on base class
print() called on derived class
derived class destructor
base class destructor
Explanation: ‘b_ptr‘ is a pointer of Base type and points to a Derived class
object. When pointer ‘ptr->print()’ is called, function ‘print()’ of Derived is
executed.
This code works because the base class defines a public interface and the
derived class overrides it in its implementation even though the derived has a
private virtual function.
classclass_name{
frienddata_typefunction_name(argument);
// syntaxof friend function.
};
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>
usingnamespacestd;
classRectangle{
private:
int length;
public:
Rectangle() {
length =10;
}
Friend int printLength(Rectangle);
//friend function
};
Int printLength(Rectangle b) {
b.length +=10;
return b.length;
}
int main() {
Rectangle b;
cout << "Length of Rectangle: " <<
printLength(b) << endl;
return 0;
}
Output:
Length of Rectangle: 20