Cpp ?
Cpp ?
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
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
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
Normal method
Qualifying the namespace name & scope resolution operator.
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 to pointer
➢ Reference to array
➢ 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.
➢ Default arguments
➢ 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
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.
➢ DMA (c++)
• Upon success it returns void. • Upon success it returns exact pointer type
• Malloc doesn’t call constructor upon • New operator call constructor upon object
object creation. creation.
Difference between malloc and new
Free Delete
• Free function does not call destructor upon • Delete operator does call destructor
object destroy. upon object destroy.
• 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.
➢ 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.
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.
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.
➢ DESTRUCTOR
• 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.
1. Copy constructor
2. Assignment overloaded operator
3. Constructor
4. Destructor
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.
• 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.
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.
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?
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”.
};
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.
Type of INHERITANCE
Derived
Derived
Derived
Derived
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.
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.
Note:
Base class pointer can point to derived class object address because inheritance
available from base class derived class.
Function binding
{ 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:
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.
➢ 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.
➢ 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.
➢ 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
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) {}