Opps in C++, Basics Of OOPs in Cpp
The main aim of oop is to bind together the data and the functions that operate on them so that no other part of the code can access this data except this function.
Class: It is a user-defined data type, which holds Its own data members & member functions, which can be accessed and used by creating an instance of that class.
Object: When class is defined no memory is allocated but when it is instantiated (i.e., an object is created) memory is allocated.
Encapsulation: In oop, Encapsulation is defined as binding together the data & the functions that Manipulates them.
Abstraction: Abstraction means displaying only essential information and hiding details
Abstraction using classes
Abstraction using Header Files (math.h-pow())
Polymorphism: In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form.
operator overloading
Function overloading
int sum(10,20,30)
Int sum(10,20)
Inheritance: The capability of a class to derive properties and characteristics from another class is called inheritance.
Subclass
Superclass
Reusability
Dynamic Binding: In dynamic binding, the code is executed in the response to the function call is decided at run time.
Constructor: A constructor is a member function of a class Which initializes objects of a class in ac + + Constructor is automatically called when the objects create.
It has the same name as class self.
Constructor Doesn’t have a return type.
Default Constructor (No Parameter Passed)
Parameterized Constructor
Copy Constructor
Destructor in C++: derived class destructor will be invoked First, then base class destructor will be invoked.
Access Modifier:
Public: can be accessed by any class.
Private: can be accessed only by a function in a class (inaccessible outside the class).
Protected: It is also inaccessible outside the class but can be accessed by a subclass of that class
Note: If we do not specify any access modifier inside the class then by default the access modifier for the member will be private.
Friend Class: A friend class can access private protected members of the other class in which it is declared as friend
Example of class B ;
Inheritance:
Syntax:
class Subclass: access mode base class
{
--------
--------
}
Single Inheritance:
Multiple Inheritance:
Multilevel Inheritance:
Hierarchical Inheritance:
Polymorphism:
Compile Time Polymorphism
Operator overloading
Function overloading
Runtime Polymorphism
Function Overriding occurs when a derived class has a definition of one or more members of the base class.
Advantages of Data Abstraction:
Avoid code duplication and inc. reusability.
Can change the internal implementation of class independently.
Structure Vs Class:
The most important difference is security. A structure is not secure and can not hide its member functions and variables while a class is secure and can hide its Programming & designing details.
Local Classes in C++: A class declared inside a function becomes local to that function and is called a local class.
All the methods of the local class must be defined inside the class only.
Virtual Function and Runtime Polymorphism:
A virtual function is a member function that is declared within a base class and redefined (overridden) by a derived class.
The function is declared with the virtual keyword in the base class.
Exception Handling in C++:
Try: represent a block of code that can throw an exception.
Catch: represent a block of code that gets executed when an error is thrown.
Throw: used to an exception.
There is a special catch block ? catch(...)
It catches all types of errors.
Inline Function:
? Inline is a request, not a command.
It is a function that is expanded in line when it is called when the inline function is called, the whole code gets inserted or substituted at the point of it function call.
Inline return-type fun()
{
--------
--------
}
Function Overloading is a feature in c++ when two or more functions can have the same name and different parameters.
void print (int i)
{
cout<<” Here is int “<
}
Void print(float i)
{
cout<<”Here is float”<
}
Int main
{
print(10);
print(10.12);
}
Difference Between C & C++ :
The structure is a collection of dissimilar elements.
Static Members in C++
Static Variable in a function:
When a variable is declared as static, space for it gets allocated for the lifetime of the Program. (default initialized to 0) even if the function is called multiple times, the space for it is allocated once.
Static Variable in a class:
Declared inside the class body.
They must be defined outside the class.
Also known as a class member variable.
Static variables don’t belong to any object, but to the whole class.
There will only is a copy of the static member variable for the whole class.
Ex:
class account
{ private:
int balance;
static float roi;
public:
Void setbalance (int b)
{
Balance = b;
}
} ;
// initialized outside class
Float Account :: roi = 3.5f ;
void main
{
Account a1;
}
The object can also be declared as static
static account a1;
Static Function in a Class: static member functions are allowed to access only the static data members or other static member functions.
Constructor:
Constructor is a special member function of the class. It is automatically invoked when an object is created.
It has no return type
Constructor has the same name as the class itself.
If we do not specify, then the C++ compiler generates a default constructor for us.
Constructor
Class_name() class_name(parameters) class_name(const
update() update(int x, int y) class_name &obj)
{ { update(const update
a=10; a=x; &p2)
b=20; b=y; { a=p2.a;
} } b=p2.b; }
The compiler generates two constructors by itself
Default Constructor
Copy Constructor
But if any of the constructors are created by the user, then the default constructor will not be created by the compiler.
Construction overloading can be done just like function overloading.
Default (compiler’s) copy constructor can be done only with shallow copy.
Deep Copy is Possible any with user-defined constructor In user-defined copy constructor, we make sure that pointers at copied objects point to new memory locations.
Can we make a copy constructor private? yes
Why does the argument to copy constructor must be passed as a reference?
Because if we pass value, then it would be made to all copy constructors which becomes non-terminating
Destructor
A destructor is a member function that destructs or deletes an object.
Destructors don’t take any argument and don’t have any return type.
Only one destructor is possible
Destructors cannot be static.
Actually, the destructor doesn’t destroy the object, it is the last function that is invoked before the object is destroyed.
Destructor is used so that before deletion of obj we can free space allocated for this resource B/C if obj gets deleted then space allocated for obj will be free but resource doesn’t
Operator Overloading
C++ has the ability to provide special meaning to the operator.
Class complex
{
------
------
Complex operator + (complex &c1)
{
Complex res;
res.a=c1.a;
res.b=c2.b;
}
}
Int main ()
{
c=c1+c2
}
As ‘+’ can’t add complex no’s directly so we can define a function with the name + but we need to write the operator keyword before it so, we can use all operators this.
Friend Class
A Friend class can access the private and protected members of other classes in which it is declared as friend.
There can befriend class and friend function.
Ex :
Class Box
{
Private:
Double width;
Public:
Friend void printwidth (Box box);
Void setwidth(double wid);
}
Void Box:: setwidth (Boxdouble wid)
{
width=wid;
}
Void printwidth (Box box)
{
cout<
}
int main()
{
Box box;
box setwidth (14);
print width (box);
Inheritance
It is a process of inheriting the properties and behavior of an existing class into a new class.
Syntax:
class Base_class
{
} ;
class der_class:visiblity_Mode Base Class
{
}
Ex:
class car
{
} ;
Class sport_car: public car
{
} ;
Types of Inheritance:
Single Inheritance:
Example:
class B: public A
{
} ;
Multilevel Inheritance:
Example:
class B: public A
{
} ;
class C: public B
{
} ;
Multiple Inheritance:
Example:
class A
{
} ;
class B
{
} ;
Class C: public A, public B
{
} ;
Hierarchical Inheritance:
Example:
class B: public A
{
} ;
class C: public A
{
} ;
Visibility Mode:
If B is subclass and visibility mode is public.
class A: public B
{
} ;
Then public members of A will be public in B, and protects will protect.
If Visibility mode is private then both protected and public members of a will be private members of B.
Is a relationship is always implemented as a public inheritance.
Constructor and Destructor in inheritance:
The first child class constructor will run during the creation of an object of the child class, but as soon as obj is created child class constructor runs and it will call the constructor of its parent class and after the execution of the parent class constructor it will resume its constructor execution.
child? B() : A() ? parent constructor call
{
}
While in case of the destructor, first child destructor exec,
Then the parent desc is executed.
Constructor exec
Obj
|
Child Constructor
|
Parent Constructor
|
Complete Parent
|
Complete Child
This Pointer
Every object in C++ has access to its own address through an important Pointer called this pointer.
Class Box
{
private:
Int l, b, h;
public:
Void set(int l,int b,int h)
{
this? l= l;
this? b= b;
this? h= h;
}
};
Int main ()
{
Box b;
b.set(5,10,4);
}
Method Overriding
(achieved at run time)
It is the redefinition of the base class function in its derived class, with the same return type and the type and same parameters.
While method overloading is achieved at compile time
Ex :
class car
{
private:
Int gear no ;
public:
Void change-gear(int gear)
{
gear ++;
}
}
class sports car: public car
{
Void change-gear(int gear)
{
if(gear>5)
gear ++;
}
}
int main
{
Sports Car &c;
&c. change-gear(4);
}
The function of the sports class will be called.
While calling change -gear(), first it checks if any fun with this home exists in the calling class, otherwise, it goes to the base class.
Useful: As we have change-gear for all except one car switch have a unique method of gear change.
Virtual Function
A virtual function is a member function that is declared with a ‘virtual Keyword’ in the base class and redeclared (overridden) in a derived class.
When you refer to an object of a derived class using a pointer to a base class, you can call a virtual function of that object and execute the derived class version of the function.
They are used to achieve Runtime polymorphism.
Virtual Function can not be static and also can not be a function of another class.
Compile-time (Early Binding) Vs Run-time (late Binding)
class base
{
Public:
virtual void print()
{
cout<<” this is base print“ <
}
Void show ()
{
cout<<” base show fun” <
}
}
Class derived
{
Public:
Void print()
{
cout<<” derived print” <
}
Void show()
{
cout<<” derived show fun” <
}
}
Int main ()
{
base * bptr;
Derived der;
b ptr = &der;
bptr ? print() ;//Run Time
bptr? show();//Compile Time
Output:
derived print// Late Binding
Base Show fun//Early Binding
During Compiler time bptr behavior is judged on the basis of which class it belongs to, so bptr represents the base class.
If the function is not virtual then it will allow binding at compile-time and print fun of base class will get bound base class.
But at run time bptr points to the object of a derived class, so it will bind the function of derived at run time.
Working of virtual Function (v table & vptr)
If a class contains a virtual function then the compiler itself does two things
A virtual Pointer (VPTR) is created every time obj is created for that class that contains a virtual function.
Irrespective of whether the object is created or not, a static array of the pointer is called VTABLE where each cell point to each virtual function is created, in the base class and derived class.
Sometimes implementation of all functions can not be pract in the base class. Such a class is called an abstract class.
A pure virtual function in C++ is a Virtual function for which we don’t have any implementation, we only declare it.
// Abstract Class
Class Test
{
Public:
Virtual void fun ()= 0 ; //pure virtual function
A Class is abstract if it has at least one pure virtual function.
We can not declare objects of an abstract class.
Ex: Test t; will show
We can have a pointer or reference of an abstract class.
We can access the other functions except for virtual by the object of its derived class.
If we don’t override the pure virtual function in the derived class then it becomes abstract.
An abstract class can have a constructor. (Read From GfG)
Template in C++
Template
Check (a , b)
{
If (a>b)
return a;
else return b;
}
It Just helps in data type so that we can write a generic function that can be used for the different data types.
Dynamic Constructor
When an allocation of memory is done dynamically Using dynamic memory allocator ‘new’ in the constructor
class geeks
{
public:
Void fun ()
{
p=new char [6] ;
}
}
Int main ()
Missing
Virtual Destructor
Deleting a derived class object using a pointer to the base class that has a non-virtual destructor resolution in undefined behavior i.e,
The destructor of the base class runs only.
Nested Class
A nested class is a member and missing such has the same access right as any other member.
The member of the enclosing class has no such access to nested class members
class encoding
{
private :
Int x ;
public:
class Nested// Run properly
{
int y;
void fun (int a)
{
x=a;
}
}
void fun1(int b)//Error ( o/c it doesn’t have access to y)
{
y=b;
}
}
The main aim of oop is to bind together the data and the functions that operate on them so that no other part of the code can access this data except this function.
Class: It is a user-defined data type, which holds Its own data members & member functions, which can be accessed and used by creating an instance of that class.
Object: When class is defined no memory is allocated but when it is instantiated (i.e., an object is created) memory is allocated.
Encapsulation: In oop, Encapsulation is defined as binding together the data & the functions that Manipulates them.
Abstraction: Abstraction means displaying only essential information and hiding details
Abstraction using classes
Abstraction using Header Files (math.h-pow())
Polymorphism: In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form.
operator overloading
Function overloading
int sum(10,20,30)
Int sum(10,20)
Inheritance: The capability of a class to derive properties and characteristics from another class is called inheritance.
Subclass
Superclass
Reusability
Dynamic Binding: In dynamic binding, the code is executed in the response to the function call is decided at run time.
Constructor: A constructor is a member function of a class Which initializes objects of a class in ac + + Constructor is automatically called when the objects create.
It has the same name as class self.
Constructor Doesn’t have a return type.
Default Constructor (No Parameter Passed)
Parameterized Constructor
Copy Constructor
Destructor in C++: derived class destructor will be invoked First, then base class destructor will be invoked.
Access Modifier:
Public: can be accessed by any class.
Private: can be accessed only by a function in a class (inaccessible outside the class).
Protected: It is also inaccessible outside the class but can be accessed by a subclass of that class
Note: If we do not specify any access modifier inside the class then by default the access modifier for the member will be private.
Friend Class: A friend class can access private protected members of the other class in which it is declared as friend
Example of class B ;
Inheritance:
Syntax:
class Subclass: access mode base class
{
--------
--------
}
Single Inheritance:
Multiple Inheritance:
Multilevel Inheritance:
Hierarchical Inheritance:
Polymorphism:
Compile Time Polymorphism
Operator overloading
Function overloading
Runtime Polymorphism
Function Overriding occurs when a derived class has a definition of one or more members of the base class.
Advantages of Data Abstraction:
Avoid code duplication and inc. reusability.
Can change the internal implementation of class independently.
Structure Vs Class:
The most important difference is security. A structure is not secure and can not hide its member functions and variables while a class is secure and can hide its Programming & designing details.
Local Classes in C++: A class declared inside a function becomes local to that function and is called a local class.
All the methods of the local class must be defined inside the class only.
Virtual Function and Runtime Polymorphism:
A virtual function is a member function that is declared within a base class and redefined (overridden) by a derived class.
The function is declared with the virtual keyword in the base class.
Exception Handling in C++:
Try: represent a block of code that can throw an exception.
Catch: represent a block of code that gets executed when an error is thrown.
Throw: used to an exception.
There is a special catch block ? catch(...)
It catches all types of errors.
Inline Function:
? Inline is a request, not a command.
It is a function that is expanded in line when it is called when the inline function is called, the whole code gets inserted or substituted at the point of it function call.
Inline return-type fun()
{
--------
--------
}
Function Overloading is a feature in c++ when two or more functions can have the same name and different parameters.
void print (int i)
{
cout<<” Here is int “<
}
Void print(float i)
{
cout<<”Here is float”<
}
Int main
{
print(10);
print(10.12);
}
Difference Between C & C++ :
The structure is a collection of dissimilar elements.
Static Members in C++
Static Variable in a function:
When a variable is declared as static, space for it gets allocated for the lifetime of the Program. (default initialized to 0) even if the function is called multiple times, the space for it is allocated once.
Static Variable in a class:
Declared inside the class body.
They must be defined outside the class.
Also known as a class member variable.
Static variables don’t belong to any object, but to the whole class.
There will only is a copy of the static member variable for the whole class.
Ex:
class account
{ private:
int balance;
static float roi;
public:
Void setbalance (int b)
{
Balance = b;
}
} ;
// initialized outside class
Float Account :: roi = 3.5f ;
void main
{
Account a1;
}
The object can also be declared as static
static account a1;
Static Function in a Class: static member functions are allowed to access only the static data members or other static member functions.
Constructor:
Constructor is a special member function of the class. It is automatically invoked when an object is created.
It has no return type
Constructor has the same name as the class itself.
If we do not specify, then the C++ compiler generates a default constructor for us.
Constructor
Class_name() class_name(parameters) class_name(const
update() update(int x, int y) class_name &obj)
{ { update(const update
a=10; a=x; &p2)
b=20; b=y; { a=p2.a;
} } b=p2.b; }
The compiler generates two constructors by itself
Default Constructor
Copy Constructor
But if any of the constructors are created by the user, then the default constructor will not be created by the compiler.
Construction overloading can be done just like function overloading.
Default (compiler’s) copy constructor can be done only with a shallow copy.
Deep Copy is Possible any with user-defined constructor In user-defined copy constructor, we make sure that pointers at copied objects point to new memory locations.
Can we make a copy constructor private? yes
Why does the argument to copy constructor must be passed as a reference?
Because if we pass value, then it would be made to all copy constructors which becomes non-terminating
Destructor
A destructor is a member function that destructs or deletes an object.
Destructors don’t take any argument and don’t have any return type.
Only one destructor is possible
Destructors cannot be static.
Actually, the destructor doesn’t destroy the object, it is the last function that is invoked before the object is destroyed.
Destructor is used so that before deletion of obj we can free space allocated for this resource B/C if obj gets deleted then space allocated for obj will be free but resource doesn’t
Operator Overloading
C++ has the ability to provide special meaning to the operator.
Class complex
{
------
------
Complex operator + (complex &c1)
{
Complex res;
res.a=c1.a;
res.b=c2.b;
}
}
Int main ()
{
c=c1+c2
}
As ‘+’ can’t add complex no’s directly so we can define a function with the name + but we need to write the operator keyword before it so, we can use all operators this.
Friend Class
A Friend class can access the private and protected members of other classes in which it is declared as friend.
There can befriend class and friend function.
Ex :
Class Box
{
Private:
Double width;
Public:
Friend void printwidth (Box box);
Void setwidth(double wid);
}
Void Box:: setwidth (Boxdouble wid)
{
width=wid;
}
Void printwidth (Box box)
{
cout<
}
int main()
{
Box box;
box setwidth (14);
print width (box);
Inheritance
It is a process of inheriting the properties and behavior of an existing class into a new class.
Syntax:
class Base_class
{
} ;
class der_class:visiblity_Mode Base Class
{
}
Ex:
class car
{
} ;
Class sport_car: public car
{
} ;
Types of Inheritance:
Single Inheritance:
Example:
class B: public A
{
} ;
Multilevel Inheritance:
Example:
class B: public A
{
} ;
class C: public B
{
} ;
Multiple Inheritance:
Example:
class A
{
} ;
class B
{
} ;
Class C: public A, public B
{
} ;
Hierarchical Inheritance:
Example:
class B: public A
{
} ;
class C: public A
{
} ;
Visibility Mode:
If B is subclass and visibility mode is public.
class A: public B
{
} ;
Then public members of A will be public in B, and protects will protect.
If Visibility mode is private then both protected and public members of a will be private members of B.
Is a relationship is always implemented as a public inheritance.
Constructor and Destructor in inheritance:
The first child class constructor will run during the creation of an object of the child class, but as soon as obj is created child class constructor runs and it will call the constructor of its parent class and after the execution of the parent class constructor it will resume its constructor execution.
child? B() : A() ? parent constructor call
{
}
While in case of the destructor, first child destructor exec,
Then the parent desc is executed.
Constructor exec
Obj
|
Child Constructor
|
Parent Constructor
|
Complete Parent
|
Complete Child
This Pointer
Every object in C++ has access to its own address through an important Pointer called this pointer.
Class Box
{
private:
Int l, b, h;
public:
Void set(int l,int b,int h)
{
this? l= l;
this? b= b;
this? h= h;
}
};
Int main ()
{
Box b;
b.set(5,10,4);
}
Method Overriding
(achieved at run time)
It is the redefinition of the base class function in its derived class, with the same return type and the type and same parameters.
While method overloading is achieved at compile time
Ex :
class car
{
private:
Int gear no ;
public:
Void change-gear(int gear)
{
gear ++;
}
}
class sports car: public car
{
Void change-gear(int gear)
{
if(gear>5)
gear ++;
}
}
int main
{
Sports Car &c;
&c. change-gear(4);
}
The function of the sports class will be called.
While calling change -gear(), first it checks if any fun with this home exists in the calling class, otherwise, it goes to the base class.
Useful: Like we have change-gear for all except one car switch have a unique method of gear change.
Virtual Function
A virtual function is a member function that is declared with a ‘virtual Keyword’ in the base class and redeclared (overridden) in a derived class.
When you refer to an object of a derived class using a pointer to a base class, you can call a virtual function of that object and execute the derived class version of the function.
They are used to achieve Runtime polymorphism.
Virtual Function can not be static and also can not be a function of another class.
Compile-time (Early Binding) Vs Run-time (late Binding)
class base
{
Public:
virtual void print()
{
cout<<” this is base print“ <
}
Void show ()
{
cout<<” base show fun” <
}
}
Class derived
{
Public:
Void print()
{
cout<<” derived print” <
}
Void show()
{
cout<<” derived show fun” <
}
}
Int main ()
{
base * bptr;
Derived der;
b ptr = &der;
bptr ? print() ;//Run Time
bptr? show();//Compile Time
Output:
derived print// Late Binding
Base Show fun//Early Binding
During Compiler time bptr behavior is judged on the basis of which class it belongs to, so bptr represents the base class.
If the function is not virtual then it will allow binding at compile-time and print fun of base class will get bound base class.
But at run time bptr points to the object of a derived class, so it will bind the function of derived at run time.
Working of virtual Function (v table & vptr)
If a class contains a virtual function then the compiler itself does two things
A virtual Pointer (VPTR) is created every time obj is created for that class that contains a virtual function.
Irrespective of whether the object is created or not, a static array of the pointer is called VTABLE where each cell point to each virtual function is created, in the base class and derived class.
Sometimes implementation of all functions can not be pract in the base class. Such a class is called an abstract class.
A pure virtual function in C++ is a Virtual function for which we don’t have any implementation, we only declare it.
// Abstract Class
Class Test
{
Public:
Virtual void fun ()= 0 ; //pure virtual function
A Class is abstract if it has at least one pure virtual function.
We can not declare objects of an abstract class.
Ex: Test t; will show
We can have a pointer or reference of an abstract class.
We can access the other functions except for virtual by the object of its derived class.
If we don’t override the pure virtual function in the derived class then it becomes abstract.
An abstract class can have a constructor. (Read From GfG)
Template in C++
Template
Check (a , b)
{
If (a>b)
return a;
else return b;
}
It Just helps in data type so that we can write a generic function that can be used for the different data types.
Dynamic Constructor
When an allocation of memory is done dynamically Using dynamic memory allocator ‘new’ in the constructor
class geeks
{
public:
Void fun ()
{
p=new char [6] ;
}
}
Int main ()
Missing
Virtual Destructor
Deleting a derived class object using a pointer to the base class that has a non-virtual destructor resolution in undefined behavior i.e,
The destructor of the base class runs only.
Nested Class
A nested class is a member and missing such has the same access right as any other member.
The member of the enclosing class has no such access to nested class members
class encoding
{
private :
Int x ;
public:
class Nested// Run properly
{
int y;
void fun (int a)
{
x=a;
}
}
void fun1(int b)//Error ( o/c it doesn’t have access to y)
{
y=b;
}
}
0 Replies to “Opps In C++ | Basics Of OOPs In Cpp”
Leave a Reply
Your email address will not be published.