0% found this document useful (0 votes)
5 views24 pages

Cpp ?

C++ is an object-oriented programming language that extends the C language, emphasizing the use of objects to encapsulate data and functions. Key features of C++ include encapsulation, data abstraction, polymorphism, and inheritance, which enhance data security, flexibility, and reusability. The document also discusses various programming approaches, differences between functions and objects, memory management, and the role of constructors and destructors in class design.

Uploaded by

rohit kumar
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)
5 views24 pages

Cpp ?

C++ is an object-oriented programming language that extends the C language, emphasizing the use of objects to encapsulate data and functions. Key features of C++ include encapsulation, data abstraction, polymorphism, and inheritance, which enhance data security, flexibility, and reusability. The document also discusses various programming approaches, differences between functions and objects, memory management, and the role of constructors and destructors in class design.

Uploaded by

rohit kumar
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/ 24

Definition: C++ is an extension & implementation of the new feature in c language.

C++ is an object-oriented programming language.

Ques: what are the programming approaches


1. Procedural-oriented: writing the instructions with the help of local variable, global
variable, functions and goto is called procedural oriented. ex-C, pascal etc.
2. Structural-oriented: writing the instructions with the help of local variable, global
variable, functions and goto and control statement is called procedural oriented. ex-
C, pascal etc.
3. Object-oriented: writing the instruction in the form of “objects” instead of sequential
instruction. Ex-C++, JAVA etc.

Ques: why C++ called as an object oriented


1. Because C++ language views the problem in the term of object oriented involved
rather then the procedure for doing it.
2. Object oriented programming (OOP) is a programming paradigm based on the
concept of “objects” which contain data in the form of field, often known as
attributes.
and codes in the form of procedure, often known as method.

Features of C++ (main features)


➢ Encapsulation: encapsulation is mechanism that bind together code and data into a
single unit (called class) and that keeps both safe from outside interference and
misuse.
OR
Wrapping up of data and functions into a single unit (called class) and this
mechanism is known as encapsulation.
Advantage- data security.

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”.

We cannot access any function from class directly. We need an object to access that function which is using the
member the variable of that class.
➢ Data abstraction: it refers to the act of representing essential features and hiding the
background details.
Advantage-data hiding.

Access specifiers
1. Public
2. Protected
3. Private
➢ Polymorphism: A single entity can exist in more than one form
In C++ polymorphism divided into 2 types.
1. Compile-time polymorphism
a) Function overloading
b) Operator overloading
2. Runtime polymorphism
a) Virtual function
Advantage-flexibility
A real-life example of polymorphism is a person who at the same time can have different characteristics. Like a man at
the same time is a father, a husband and an employee. So the same person exhibits different behavior in different
situations. This is called polymorphism

➢ Inheritance: inheritance is a process by which one object inherits the properties of


another object belonging to another class.
• Here the new class can be built from the old one the original is known as the base
class & new class is referred to as derived class.
Advantage: reusability & extensibility

Consider a group of vehicles. You need to create classes for Bus, Car, and Truck. The methods fuel Amount (),
capacity (), applyBrakes () will be the same for all three classes. If we create these classes avoiding inheritance
then we have to write all of these functions in each of the three classes.

Ques: Difference b/w scanf & printf comparing with cat & cin
1. Printf & scanf both are library functions
1. Cout and cin both are objects of classes

2. Printf and scanf needs format specifiers


2. Cout and cin doesn’t require specifiers

3. Printf and scanf returns value.


3. Cout and cin doesn’t return any value.
4.printf and scanf doesn’t support user defined variable directly to scan & printf.
4.cout & cin does support user defined variable directly to scanf & printf with help of
operator overloading.

➢ Scope Resolution operator

Scope resolution operator is used to access global variable.


Symbol - : :

When to use?
1. Whenever local & global are of same name.
2. When function definition is outside the class.
3. Namespace
4. Class inside the class.
5. Inheritance

Ex-
Using namespace std;
Int x=200;
Main ()
{
Int x=100;
Cout<<” local variable-” <<x<<endl;//x=100
Cout<<” global variable” <<::x<<endl;//x=200
}

➢ Namespace

1. Namespace is a declarative region, that provides scope to the identifiers (types of


names, variable, functions and templates).
2. Namespace is a block.
3. A namespace creates a memory in which various program elements can be placed.
4. Elements declared in one namespace are separated from the elements declared in
another.
Using namespace std
Keyword standard lib contains declaration, cout, cin, endl etc
Block

Ques-Can we write program without using namespace?


Yes, but have to include std:: in each and every line.

We can use both as well


1. :: std
2. Using namespace std;
Ex-the best example of the namespace is the C++ standard library, where all the class,
functions and templates are declared.
Ques-where we are using namespace?
When we use two functions with same name to avoid the conflict, we use namespace.

Different ways to access namespace


1. Normal method
2. Using directive method
3. Using declarative method

Normal method
Qualifying the namespace name & scope resolution operator.

Using directive method


It allows all the namespace name to be used without the namespace name as an explicit
Qualifier.
Ex-using namespace first;
Using declarative method
Using declarative allows an individual name to used without qualification.
Ex-using first::x using second::x

Ques-redefinition of namespace is possible or not?


It is possible but the variable inside one block should not same in the second block (when
we redefine same namespace).
Namespace first {
Int x=100;
Int y=200;
}
Namespace first {
Int x=300;//error because we have already x value declared in first namespace.
Int z=400;
}

Alias name for namespace (duplicate name)


Syntax for alias namespace
Namespace name= existing namespace name

➢ DATA TYPE IN C++

1. bool.
2. Wchar_t.
3. string

1. bool
• size of the bool is 1byte.
• Bool represents in (0 and 1) only.
• 0 means false,1 means true.
• By default, bool datatype is false (0).
• Bool is also called as Boolean expression/Boolean data type.

2. Wchar_t
• It is universal code/universal language/wide character.
• Size of wchar_t is depending on the compiler (2bytes or 4bytes).
• Syntax: wchar_t variable_name.
• For scan & print wchar_t we have to use wcin>> and wcout<<.

3. string
• C++ has in its definition a way to represent a sequence of characters as an object of
the class. This class is called std:: string. String class stores the characters as a
sequence of bytes with the functionality of allowing access to the single-byte
character.
• In the case of strings, memory is allocated dynamically. More memory can be
allocated at run time on demand. As no memory is pre allocated, no memory is
wasted.

Reference variable
It is used to provide duplicate name/alias name for existing variable.
Syntax: data type &new_name=existing name.
Ex-int x=10;
Int &rv=x; (rv is another name to x)

• Reference variable must be initialized at the time of declaration.


Int x=10; Int &rv;
rv=x;//error
• Separate memory won’t be created for reference variable.
• NULL reference is not possible. Int &rv=0//error
• In its life time, reference variable can’t refer to another variable.
• Reference variable cannot refer to constant
Int &rv=123;//error
Const int &rv=123;//no error
• Reference variable will get dereference automatically.

➢ Reference to pointer

Syntax: data type *&new_name=existing name.


Ex-int x=10,*q;
Int *p=&x;
Int *&rv=p;//rv is another name for pointer p;
Cout<<*rv<<’’ ”<<*p<<endl;
rv=&q;//invalid

Note: Pointer to reference is not possible


Creating pointer to hold reference address but reference variable doesn’t have their
own address.

➢ Reference to array

Syntax: data type (&new_name) [size]=existing name.


Ex-int a [5] = {1,2,3,4,5}
int (&p) [5] =a: p is reference variable to an array of 5 integers
Note: array to reference is not possible, we cannot create array to hold 5 reference
variable because reference variable doesn’t have any separate memory.

Passing Arguments to the function


➢ Call be value
A copy of actual arguments is passed into the formal arguments of the called
function and any change made to formal arguments in the called function have no
effect on the value of actual arguments in the calling function.

➢ Call be address
The location/address of actual arguments is passed to formal arguments of the
called function. This means by accessing the address of actual arguments we can
modify them within the called function.

➢ Call be reference
Copies of reference of an actual argument passed into the formal parameter inside
the function, the reference is used to access the actual argument used in the call.
The change made to the reference variable passed in formal parameter will affect
the actual arguments.

Difference b/w reference and pointer


Reference Pointer

• Reference variable must be initialized. • Pointer may or may not be initialized.

• Null reference is not possible. • Null pointer is possible.

• • inPointer can point to any variable at any time.


Reference variable cannot refer to another variable
its lifetime.
• Pointer will get separate memory.
• Reference variable will not get separate memory.
• Reference variable will de-reference implicitly.
• pointer variable will get de-reference explicitly.
➢ Function overloading
Compiler follow name mangling to handle n-number of functions with same name.
Definition-overloading refers to the capability of using a single name for different
task.
• Defining multiple functions with same name is called function overloading.
these functions must differ in their name, order or type.
• In function overloading function call finds the exact match of function in which
the formal and actual argument matches in number and type. `
Note: a function can’t be overloaded on the basis of function return type.

• Function overloading follows name mangling


Name mangling-name mangling is the process used by c++ compilers, that
changes name of every function (those have same name) by adding additional
information based on function name & its argument.

➢ Default arguments

A default argument is a function parameter that has a default value provided to


it. If the user doesn’t supply a value for this parameter the default value will be
used.
if the user does supply a value for the default parameter the user supplied value
is provided.

Rule for default arguments


1. A function can have multiple default parameters.
2. All default parameters must be the right most parameters.
3. Default parameter must be given only in the function prototype and must
not be repeated in the function definition.

Ambiguous: a situation is referred to ambiguous when is compiler is unable to


choose the one among two or more overloaded function.

➢ INLINE FUNCTION
In line function is a function where a function call is replaced with the function definition.
Syntax: Inline return type func_name (arguments).
Inline function may not work.

• If function is recursive.
• If the function having control statement.
• If function having return keyword (expect void).
➢ Difference between macro and inline function

Macro Inline function

A macro is a piece of code in a program that is A function call replaced by function


replaced by the value of the macro. definition.

Macros are expended by the pre-processor. Inline functions are passed by translators.

Macro can have N n.o of instructions. Inline function can have less instruction.

#define keyword is use to write macros Inline keyword is use

➢ DMA (c++)

• Dynamic memory allocated in C++ by new.


• Dynamic memory is deallocated by delete operator.
New
Syntax: new data_type; //for variable
ex-new int. new int (56)//initialized dma
new data_type [size]; //for array
ex-new int [5]. new int [5] {2,5,3,5,1};//initialized dma

➢ Difference between malloc and new


Malloc New

• Malloc is a library function. • New is an operator.

• Malloc needs library. • New doesn’t need library.

• Upon success it returns void. • Upon success it returns exact pointer type

• Upon failure it returns zero. • Upon failure throw an exception runtime


error.
• Memory initialization not possible. • Memory initialization possible.

• Malloc doesn’t call constructor upon • New operator call constructor upon object
object creation. creation.
Difference between malloc and new

Free Delete

• Free is a library function. • Delete is an operator.

• Free function overloading not possible. • Delete operator overloading possible.

• Free function does not call destructor upon • Delete operator does call destructor
object destroy. upon object destroy.

➢ Why the size of empty structure size is 1 byte in c++

To show the variable existence.


Ex-using namespace std;
Struct study {
Void test ()
{
Cout<<”test in struct”<<endl;
}
}
Note: in above program there is no structure member so it will not create any memory but
for accessing the test function we need memory that’s why c++ empty structure size is of 1
byte.

➢ CLASS and OBJECTS


Class is collection of data members and member functions.

• Size of the class depends only on the data members of class not on member
functions.
• The size of empty class is one byte.
• By default ,all the member of class are present in private sections.
Syntax: class student {
Data members;
Member functions;
};

Object:
Object is variable of class.
Object is physical existence of class.
Object is real world entity.

Ex-using namespace std;


Class family
{
Int cash, gold;
Public:
Void set_data (int a, int b)//this pointer will present internally to catch object
address.
{
Int cash=a;gold=b;
}
}
Int main ()
{
Family f1, f2;
f1.set_data (10,20)//family :: set_data (10,20,&f1);
}

➢ This pointer
• C++ provide a unique pointer called this pointer.
• The pointer called this pointer, points to object itself.
• Whenever a member function is called, this pointer automatically passed to the
called member function as an implicit, inbuilt argument.
• A static member function is a part of class but not the part of object therefore a
static member function does not have this pointer.

➢ CONSTRUCTOR AND DESTRUCTOR

A constructor is a special member function of class which is invoked automatically when an


object of the same class is created, the object is automatically initialized by constructor.
Syntax: class name ();
Characteristics
• A constructor has same name as the class to which it belongs.
• It doesn’t have any return type not even void.

• A constructor can have default arguments.


• Constructor can be overloaded.
• A constructor can’t be inherited although a derived class can call base class
constructor.

NOTE: constructor having this pointer because constructor is a member function.

Ques-How many times constructor will call for an object?


Only one time, at the time of object creation.

Type of constructors
1. Default constructor.
2. Parameterized constructor
3. Copy constructor.

Ques-why constructors do not have any return type and can have arguments?

Basically, constructors are called when an object is created and there can never exist a
situation where we have to return a value at the time of creation of an object.
But there may situations when data member of different object must be initialized with
different value at the time of creation.

A copy constructor is called in 3 situations

1. When an object is used to initialized another object.


2. When object is passed as a parameter to a function where a copy of the object is
created to the function to operate on.
3. When a function returns an object to create a copy of the value returned by the
function.

➢ SHALLOW COPY and DEEP COPY

SHALLOW COPY: copy one object data into another object with the help of copy constructor
and assignment overloaded operator then it is called as shallow copy.

• In shallow copy if object contains pointer to dynamically allocated memory, then it will
not support properly.
• If an object modifies then another object also modifies, because both objects are
pointing to same memory location.

DEEP COPY: copy one object data to another object with the help of user provided copy
constructor or assignment overloaded operator function is called deep copy.

• In deep copy if object having pointer to dynamically allocated memory, then both
objects are pointing to different memory location.
• In deep copy if one object is modified it will not affect for another object.

Ques-why copy constructor collecting the argument with reference type only.
If copy constructor collects the argument with non-reference type, then copy constructor
will called recursively and leads to get segmentation fault at run time.
To avoid this type of problem it is restricted to compiler that copy constructor must collect
argument with reference type.

➢ Dynamic constructor

• Dynamic constructor is used to allocate the memory to the object at the run time.
• The memory allocation to the object is allocated with the help of new operator.
Ex-Class A {
};
Main ()
{
A *Ptr;//constructor is call for object only not for pointers.
Ptr=new A;// call default dynamic constructor
Ptr=new A (10,20) ;// call parameterized dynamic constructor
}.
Difference between member function and constructor?
Constructor Member function

• Constructor name is same as class name. • Member function can have any name.

• Constructor doesn’t have any return type. • But member function can have return type.

• Constructor is used to create and initialize • Member function is used to access and modify
object. data members of class.
• Constructor will call only once to the object. • Member function can call N n.o of times.
• Constructor does call automatically. • Member function does call explicitly.

• Constructor can’t be constant and static. • Member function can be static or constant.

➢ FRIEND FUNCTION

Friend function is a non-member function where it can access private and protected
data member of a class.

Syntax: friend return type func_name (arg);

• Friend function can be friend of N number of classes.


• A class can N number of friend functions.
• Friend functions will not have this pointer.
• Friend keyword we can only use while declaring friend function not in definition of
function.

➢ DESTRUCTOR

A Destructor is a special member function of a class which is invoked automatically to


destroy the object when the scope of the object is completed.

Syntax: ~class name (void);

• A destructor will not return any value and does not accept arguments and therefore
it cannot be overloaded.
• A destructor cannot be declared as static, const or volatile.
• A destructor should be declared in public section.
• It is necessary that a destructor use a delete expression to de allocate the memory if
constructor in program uses the new for allocating memory,
• A destructor called in the reverse order of its constructor invocation.

➢ Difference between destructor and constructor?


Destructor Constructor
• destructor destruct the object • constructor construct the object.
• it is not possible to pass argument to the • we can pass argument to the
destructor. constructor.
• Destructor overloading not possible. • Constructor overloading is possible.
• Constructor execution starts in sequence • It will execute in reverse manner.
manner.

Default member function of a class

1. Copy constructor
2. Assignment overloaded operator
3. Constructor
4. Destructor

➢ Constant member function

Constant member function is a member function where the data members are constant.
Syntax: return type func_name (arg) const

Mutable: it is a keyword, uses to remove the consent behaviour from the variable, so that we
can modify the variables in const functions.

➢ STATIC DATA MEMBER

• It is like a global variable for its class, it is available to all object of that class.
• Default value of static member is zero.
• Just one copy of this data member is created for entire class since it is shared by all the
object of that class.
• A static data member must be
1. Declare within the class
Class info {
Static int count;//declaration
};
2. Defined outside the class specifying the type and scope of the static member
variable as
Int info::count//definition
This is compulsory since static member variable are stored separately and not as a
part of an object.
➢ STATIC MEMBER FUNCTION
• Static member functions are similar to ordinary function declaration.
• A static member function can access only static members of same class.
• A static member function can be invoked by using the class name instead of its objects.

Class name::function_name;

• Static member function doesn’t have any implicit “this” pointer at the first parameter.

ADVANTAGE

• The static function can be called without an object of the class and this is useful to define
constructor in private section.
• The static data member can be used to count number of objects of a class and can be
return, value of static variable using static member function.

➢ OPERATOR OVERLOADING

C++ provides the facility of giving special meaning to an operator without changing the existing
meaning is referred to as operator overloading.

An operator can be overloaded by creating a special function called operator function, which
describes the task.

Syntax: return-type operator op (arg)


{
-----------
------------
}
Where- op=+,-,=,% etc;

➢ Friend function can not be used to overload the following operators.


1. = (assignment)
2. ()-function call
3. [ ] (subscript)
4. → (arrow)

Ques-Why =operator can’t be overloaded with friend function?

When we don’t define the member function for ‘ =’ operator then compiler will supply the default
assignment operator overloaded function, and if we define the friend function then it becomes
ambiguity for compiler.

Compiler only provides 4 default functions


Constructor.
Destructor.
Copy constructor.
Assignment operator.

OPERATORS THAT CAN BE OVERLOADED ONLY BY FRIEND FUNCTION

There are two operators that can be overloaded only though friend function and can not by using
member function.

• << (insertion)
• >> (extraction)

Ques-why ‘<<’ & ‘>>’ operators can’t be overloaded with number functions?

Suppose if the instruction is


Cout<< obj;
And whenever it is overloaded as member function, then it is interpreted as
Cout. Operator<<(obj);
It would require that your overloaded function be part of the ostream class, not part of your class.
since you are not allowed to modify the ostream class.

Ques- why cout and cin are being passed as reference object while overloading insertion and
extraction operators?

Ans: as the copy constructor and overloaded assignment operator in the class ‘ostream’ and
‘ostream’ are declared in the protected section, their object cout and cin are passed as reference.

Ques-why cout and cin are being passed as reference object while overloading insertion and
extraction operators?

If cout and cin are passed as non-reference objects then a new object is being created on the stack
or data sections and tries to call the copy constructor of ‘istream’ and ‘ostream’ which are in the
protected section as they are declared in the protected section, the copy constructor can not be
called outside the class scope.

➢ INHERITANCE

Inheritance is the process of acquiring the properties of one class into another class.

In this process, new classes are created called “Derived class” and the existing classes known as
“base class”.

Syntax: class base


{
};
class derived: public/protected/private base
{

};

FEATURES

• The derived class object automatically inherits the features of the base class.
• The derived class may also possess additional features apart from those inherits from base
class.
• A class can be derived from different base classes.
• The size of base class depends only on base class data members.
• The size of derived class depends on base class data members as well as derived class data
members.
• By default, mode of inheritance is private.
• Base class all the members are inherited to derived class except private data members.
• Base class private data can’t be inherited (it is not possible to access base class private data
directly in derive class, it is possible only with help of base class members).
• Base class object only access base class members, derived class object can access base as
well as derived class data.
• Even though the base class private members are not inherited then also memory layout will
be created for derived class object depends on the base class member as well as derived
class members.

Conversion table from base to derived class

Base class Derived class MOI (mode of inheritance)

Visibility public Protected private

Public Public protected private

Protected Protected protected private

private Can’t be Can’t be Can’t be


inherited inherited inherited

Type of INHERITANCE

1. Single inheritance: derivation of a class from only one base class.


BASE

Derived

2. Multi-level inheritance: derivation of a class from another derived class.


Base

Derived

Derived

3. Multipath inheritance: derivation of a class from several base classes.

Base1 Base2 Base3

Derived

4. Hybrid inheritance: derivation of a class involving more than one form of


inheritance.
Base

Derived Base

Derived
5.
6.
7.
8.
9.
10.
11. Hierarchical inheritance: derivation of several classes from a single base class.

12. Multipath inheritance: derivation of a class from other derived class from same
base class.

Base

Derived1 Derived2

Derived3

➢ Function overriding

Designing a function in base class as well as in derived class with same parameter is called as
function overriding.

➢ How constructor and destructor behave in Inheritance.

Base class constructor and destructors are not inherited to derived class.

Note: every derived class constructor will have base class constructor call and every derived
class destructor will have base class destructor call to initialize and de-initialize data members

of base class.
~Derived()
#include<iostream> {
using namespace std; cout<<"Derived destructor"<<endl;
class Base{ }
};
int x;
public:
Base() main()
{ {
cout<<"base constructor"<<endl; Derived d1;
x=10; // d1.Base::get_data();
} // d1.get_data();
void get_data() }
{
cout<<"base="<<x<<endl;
}
~Base()
{
cout<<"Base destructor"<<endl;
} Output- base constructor
};
class Derived:public Base Derived constructor
{
int y;
public:
Derived destructor
Derived()
{ Base destructor
cout<<"derived
constructor"<<endl;
y=30;
}

Ques-Why base class constructor and destructor are not inherited to Derived class?

Because if base class constructor will inherit in derived class, then it will no more
instructor, it acts as member function.
The scope of constructor & destructor is belonged to same class to initialize and de-
initialized data members of same class.
Even though base class constructor & destructor not inherited then also every derived
class constructor destructor will have internally base class constructor call and
destructor call.

➢ VIRTUAL BASE CLASS


The virtual base classes are used to avoid duplication of data.
When the class parent is made a virtual base class, compiler make sure that only one copy of
the base class parent is inherited.

Note:
Base class pointer can point to derived class object address because inheritance
available from base class derived class.

Function binding

By default, function binding happens at compile time


Function call search for function definition at compile time is called compile time
function binding.

Using namespace std; Main () {

Class Base { Derived d1;


d1.test ();
Public:
}
Void test () {
Case 2:
Cout<<”test in base class” <, endl; Main () {
} Base *bptr;
Derived d1;
}; Bptr=&d1;//valid
Class Derived: public Base }

{ Case 3
Main () {
Public:
Derived *dptr;
Void test () { Base b1;
Dptr=&b1//invalid, because there is no
Cout<<”test in Derived class” <<endl;
inheritance from derived to base.
} }

};

Case 4:

Main () { o/p-test in base//unexpected


Base *bptr;
Derived d1;
bptr=&d1; // this will execute at runtime after memory allocation
bptr→test (); // this will execute at run-time after memory allocation, but compiler
will try to find test function definition at compile time.
}

By default, first it will try to check test function definition in base class and if compiler
found then it then it will bind that function definition at compile time.
To avoid this situation, we use virtual function.

In above example If we have to called test function in derived by using base class
pointer then we use virtual function.
➢ virtual function
virtual functions are c++ language feature to achieve run-time polymorphism.
Virtual function is a member function that is declared within a base class and redefined
by derived class to suit its own needs.

• When a function is made virtual, the decision as to which function is called is


done at the run-time based on the type of the object pointed by the pointer,
rather than the type of the pointer.
• Base class pointer can point to derived class object.in this case using base class
pointer if we call same function which is present with same name in both
classes, then base class function will be invoked.
But if we want to invoke derived class function using base class pointer, it can
be achieved by defining the function at virtual in base class, this is virtual
supports run-time polymorphism.

➢ virtual Table

to implement virtual function, c++ uses a special form of late binding known as the
virtual table created in compile time.
The virtual table is a look up table of addresses of only the virtual functions in
corresponding classes to resolve the functions with the proper function call.

• For every class separate virtual table will be created.


• Only one virtual table present for each class.
• Virtual table contains all the virtual function address.
• In a base class if the function is virtual then derived class overridden function
automatically behaves like virtual function.

Rules of virtual function:

• Virtual function must non-static.


• The virtual function is accessed by using pointers to object.
• Constructor cannot be virtual but destructor can be virtual.
Because constructor execute before object creation & virtual function execute
at run-time after execution.

➢ What happened when we write virtual constructor.

• Without constructor execution object won’t be created.


And without object virtual function cannot access object information.
• There is no use of virtual function without object.
• If we combine virtual & constructor as a single property (virtual constructor)
Then it fails to create object, due to which ambiguity happens because
compiler unable to decide which property needs to follow.

➢ virtual Destructor
virtual destructor is a destructor which is defined in base class it is used to get proper
destructor calls from derived class to base class, when the base class pointer holding derived
class dynamic object.
Virtual destructor ensures that the object resources are released in the reverse order of an
given object being constructed with respect to inherited object.

Pure virtual function


The virtual function that is declared but not defined in a base class is referred to as a pure
virtual function.
Syntax:
Virtual return-type function-name (arg…) =0;
➢ Abstract class
If a class contains at least one pure virtual function is called as Abstract class.
If a virtual function declared as pure, it must be redefined in each derived class, else
compilation of the program is unsuccessful.
Note: a class having pure virtual function cannot be used to create object of its own.

➢ Object slicing

While assigning derived class object to base class object then extra features of derived
class object are sliced off from object is called object slicing.

➢ Exception handling:
• Exception, which occurs at run-time due to unusual condition.
• To handle such exception, exception handling mechanism is used.
• This mechanism uses three keywords i.e., try, throw, catch.
• Exception is an event which occurs during the execution of program that
interrupt normal flow of program in execution.
• A try block will throw an exception using throw keyword.
• Catch block will handle the exception condition which is sent by throw.
• Some situation where try blocks may produce various type of exception.
• Can write catch block which can handle all type of exception.
Catch (…) {}
➢ Templets

• Templets are the features of the programming language that allows


functions and classes to operate with generic types.
• This allows a function or class to works on many different data type.
• To overcome the disadvantage of the function overloading.

Type of templets
1. Function templates.
2. Class templates.

Function templates: function templets are special functions that can operate with
generic types.
This allows us to create a function templet whose functionality can be adopted to more
than one type or class without repeating the entire code for each type.
Syntax:
template <class type>
return-type function-name (type T) {}

You might also like