OOPc++ Standard
OOPc++ Standard
Overview
1) What is OOP ?
Polymorphism - Polymorphism is the ability to exist in many forms. Example : We can take a boy as a
real-world example. This boy can be a student, a player, and a writer. So that this boy can exist in
different ways in different situations.
Inheritance - Inheritance means it allows classes to inherit common properties from the parent class.
Example :let's take another parent class as Animals. Here also we can inherit common properties like
name, sound, color, breed from Animal class and create classes like Dog, Cat, Horse and etc.
Encapsulation - Encapsulation means it binds data and code together into one unit. Example : the
most commonly used example is the medical capsule. This capsule mixes few types of medicines and
stored in one capsule.
Abstraction - In abstraction, it displays only the important information by hiding the implementation
part. Example : The next example is the most commonly used mobile phones. On a mobile phone,
we can perform so many actions like making a call, sending messages, take pictures, download
software and etc. We perform a lot of things but here also we don't know the inside process of these
things. Which means the implementation parts are hidden.
Classes
1) Difference Between Structure and Class in C++
Class Structure
4. It is declared using
4. It is declared using the class keyword.
the struct keyword.
5. It is normally used for data abstraction and further 5. It is normally used for the
inheritance. grouping of data
6. NULL values are possible in Class. 6. NULL values are not possible.
7. Syntax: 7. Syntax:
}; };
2) Access Modifiers
One of the main features of object-oriented programming languages such as C++ is data hiding. The
access modifiers of C++ allows us to determine which class members are accessible to other classes
and functions, and which are not.
1) Public - The public members are accessible from any part of the program.
#include <iostream>
using namespace std;
// define a class
class Sample {
// public elements
public:
int age;
void displayAge() {
cout << "Age = " << age << endl;
}
};
int main() {
// declare a class object
Sample obj1;
cout << "Enter your age: ";
// store input in age of the obj1 object
cin >> obj1.age;
// call class function
obj1.displayAge();
return 0;
}
2) Private - The private members can only be accessed from within the class. However, friend classes
and friend functions can access private members.
#include <iostream>
using namespace std;
// define a class
class Sample {
// private elements
private:
int age;
// public elements
public:
void displayAge(int a) {
age = a;
cout << "Age = " << age << endl;
}
};
int main() {
int ageInput;
// declare an object
Sample obj1;
cout << "Enter your age: ";
cin >> ageInput;
// call function and pass ageInput as argument
obj1.displayAge(ageInput);
return 0; }
Enter your age: 20
Age = 20
In main(), the object obj1 cannot directly access the class variable age.
// error
cin >> obj1.age;
3) Protected - The protected members can be accessed within the class and from the derived class.
#include <iostream>
using namespace std;
// declare parent class
class Sample {
// protected elements
protected:
int age;
};
int main() {
int ageInput;
// declare object of child class
SampleChild child;
cout << "Enter your age: ";
cin >> ageInput;
// call child class function
// pass ageInput as argument
child.displayAge(ageInput);
return 0;
}
private Yes No No
Simple functions - All the general member functions, which are of below given form
#include <iostream>
using namespace std;
class Shape{
public:
// Simple Member Function
int square(int length){
return length*length;
}
}
Static functions - Static Functions are created using static keyword before the return type of function
declaration. Static Functions can only call static members and static functions inside the static
function definition because Static members functions do not have implicit this argument. We can
direct call Static Functions without creating an object of the class. Using the scope resolution
operator (::) we can call the static function directly.
#include <iostream>
using namespace std;
class Box
{
private:
static int length;
static int breadth;
static int height;
public:
static void print()
{
cout << "The value of the length is: " << length << endl;
cout << "The value of the breadth is: " << breadth << endl;
cout << "The value of the height is: " << height << endl;
}
};
// Driver Code
int main()
{
Box b;
cout << "Static member function is called through Object name: \n" << endl;
b.print();
cout << "\nStatic member function is called through Class name: \n" << endl;
Box::print();
return 0;
}
Const functions - Constant Functions are functions that are not able to modify data members of the
class. We can declare Const Function using the const keyword at the end of the arguments
parenthesis. The syntax of the Const Function is given below.
#include <iostream>
using namespace std;
class Demo {
int x;
public:
void set_data(int a) { x = a; }
// constant member function
int get_data() const
{
// Error while attempting to modify the data
// member
++x;
return x;
}
};
main()
{
Demo d;
d.set_data(10);
cout << endl << d.get_data();
return 0;
}
Inline functions - Inline Functions are created using the inline keyword before the return type of the
function declaration. Inline Functions are used to reduce overhead function calling. Inline Function
may increase efficiency of the code if it has a small definition.
If a function is recursive.
If a function return type is other than void, and the return statement doesn’t exist in a function body.
#include <iostream>
using namespace std;
inline int square(int length){
return length*length;
}
int main(){
std::cout << square(10) << std::endl;
return 0;
}
Friend functions - Friends Functions are functions that have their definition outside (non-member
function) of the class but they can still access private and protected members of the class. To access
private and protected members outside the class definition of the Friend Function should be inside
the class. Friend Functions are declared inside the class using a friend keyword before the return
type of the function.
Friend Functions is a reason, why C++ is not called as a pure Object Oriented language. Because it
violates the concept of Encapsulation.
#include <iostream>
using namespace std;
class Shape{
int length; // private member of the class
public:
// friend function declaration
friend int square(int len);
};
// definition of friend function
int square(int len){
Shape s;
s.length=len; // access private variable
return s.length*s.length;
}
int main(){
std::cout << square(10) << std::endl;
return 0;
}
4) Constructor - Constructor in C++ is a special method that is invoked automatically at the time
of object creation. It is used to initialize the data members of new objects generally. The constructor in
C++ has the same name as the class or structure. constructors do not return value, hence they do not
have a return type. A constructor gets called automatically when we create the object of the class.
Constructors can be overloaded. A constructor can not be declared virtual.
Types of Constructor
1)Default Constructor - A default constructor is a constructor that doesn’t take any argument. It has
no parameters. It is also called a zero-argument constructor.
#include <iostream>
using namespace std;
class construct {
public:
int a, b;
// Default Constructor
construct()
{
a = 10;
b = 20;
}
};
int main()
{
// Default constructor called automatically
// when the object is created
construct c;
cout << "a: " << c.a << endl << "b: " << c.b;
return 1;
}
#include <iostream>
using namespace std;
class Point {
private:
int x, y;
public:
// Parameterized Constructor
Point(int x1, int y1)
{
x = x1;
y = y1;
}
int getX() { return x; }
int getY() { return y; }
};
int main()
{
// Constructor called
Point p1(10, 15);
// Access values assigned by constructor
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
return 0;
}
3)Copy Constructor - A copy constructor is a member function that initializes an object using another
object of the same class.
#include <iostream>
using namespace std;
class Sample {
int id;
public:
// parameterized constructor
Sample(int x) { id = x; }
void display() { cout << "ID=" << id; }
};
int main()
{
Sample obj1(10);
obj1.display();
cout << endl;
// creating an object of type Sample from the obj
Sample obj2(obj1); // or obj2=obj1;
obj2.display();
return 0;
}
5) Destructors
Destructor is an instance member function that is invoked automatically whenever an object
is going to be destroyed.
Destructor has the same name as their class name preceded by a tilde (~) symbol.
It is not possible to define more than one destructor.
The destructor is only one way to destroy the object created by the constructor. Hence
destructor can-not be overloaded.
Destructor neither requires any argument nor returns any value.
the constructor should always be non-virtual. But virtual destructor is possible.
#include <iostream>
using namespace std;
class Test {
public:
// User-Defined Constructor
Test() { cout << "\n Constructor executed"; }
// User-Defined Destructor
~Test() { cout << "\nDestructor executed"; }
};
main()
{
Test t;
return 0;
}
Objects
1) Difference between object and class.
2) Object is a real world entity such as pen, Class is a group of similar objects.
laptop, mobile, bed, keyboard, mouse, chair
etc.
7) There are many ways to create object in There is only one way to define class in
java such as new keyword, newInstance() java using class keyword.
method, clone() method, factory method
and deserialization.
Let's see some real life example of class and object in java to understand the difference
well:
Polymorphism
1) What is Polymorphism ?
The word “polymorphism” means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form.
A. Function Overloading - When there are multiple functions with the same name
with same class but different parameters, then the functions are said to be
overloaded, hence this is known as Function Overloading. Functions can be
overloaded by changing the number of arguments or/and changing the type of
arguments.
#include <bits/stdc++.h>
using namespace std;
class Geeks {
public:
// Function with 1 int parameter
void func(int x)
{
cout << "value of x is " << x << endl;
}
// Driver code
int main()
{
Geeks obj1;
B. Operator Overloading
#include <iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i = 0)
{
real = r;
imag = i;
}
// Driver code
int main()
{
Complex c1(10, 5), c2(2, 4);
A. Function Overriding
Function Overriding occurs when a derived class has a definition for one of the
member functions of the base class. That base function is said to be overridden.
#include <iostream>
using namespace std;
class Shape {
public:
void draw() {
cout << "drawing..." << endl;
}
};
int main() {
Shape* s;
s = new Rectangle();
s->draw();
s = new Circle();
s->draw();
s = new Triangle();
s->draw();
return 0;
}
Output
drawing...
drawing...
drawing...
2) Virtual Function
C++ virtual function is a member function in the base class that you redefine in a derived class. It is
declared using the virtual keyword. It is used to tell the compiler to perform dynamic linkage or late
binding on the function.
There is a necessity to use the single pointer to refer to all the objects of the different classes. So, we
create the pointer to the base class that refers to all the derived objects. But, when base class
pointer contains the address of the derived class object, always executes the base class function.
This issue can only be resolved by using the 'virtual' function.
#include <iostream>
using namespace std;
class Shape {
public:
virtual void draw() {
cout << "drawing..." << endl;
}
};
int main() {
Shape* s;
s = new Rectangle();
s->draw();
s = new Circle();
s->draw();
s = new Triangle();
s->draw();
return 0;
}
Output
drawing rectangle...
drawing circle...
drawing triangle...
3) Virtual Class
Virtual base classes are used in virtual inheritance in a way of preventing
multiple “instances” of a given class appearing in an inheritance hierarchy when
using multiple inheritances.
#include <iostream>
using namespace std;
class A {
public:
A() // Constructor
{
cout << "Constructor A\n";
}
};
int main() {
D object; // Object creation of class D.
return 0;
}
Output:-
Constructor A
By definition, a C++ abstract class must include at least one pure virtual
function. Alternatively, put a function without a definition.
You cannot make an object of the abstract class type. However, pointers and
references can be used to abstract class types.
#include <iostream>
using namespace std;
// Abstract class
class Shape {
protected:
float dimension;
public:
void getDimension() {
cin >> dimension;
}
// pure virtual Function
virtual float calculateArea() = 0;
};
// Derived class
class Square : public Shape {
public:
float calculateArea() {
return dimension * dimension;
}
};
// Derived class
class Circle : public Shape {
public:
float calculateArea() {
return 3.14 * dimension * dimension;
}
};
int main() {
Square square;
Circle circle;
return 0;
}
Inheritance
Inheritance in Java is a mechanism in which one object acquires all the properties
and behaviors of a parent object.
Note:
Single inheritance
Multiple inheritance
Hierarchical inheritance
Multilevel inheritance
Hybrid inheritance
Encapsulation
Encapsulation in C++ is defined as the wrapping up of data and information in a
single unit. Encapsulation is defined as binding together the data and the
functions that manipulate them.
2) Data binding: Encapsulation is the process of binding the data members and
the methods together as a whole, as a class.
Advantage of Encapsulation :
The main advantage of using of encapsulation is to secure the data from other
methods, when we make a data private then these data only use within the
class, but these data not accessible outside the class.
#include <iostream>
using namespace std;
// declaring class
class Circle {
// access modifier
private:
// Data Member
float area;
float radius;
public:
void getRadius()
{
cout << "Enter radius\n";
cin >> radius;
}
void findArea()
{
area = 3.14 * radius * radius;
cout << "Area of circle=" << area;
}
};
int main()
{
// creating instance(object) of class
Circle cir;
cir.getRadius(); // calling function
cir.findArea(); // calling function
}
Abstraction
Data Abstraction is a process of providing only the essential details to the
outside world and hiding the internal details
How to achieve :
#include <iostream>
#include<math.h>
using namespace std;
int main()
{
int n = 4;
int power = 3;
int result = pow(n,power); // pow(n,power) is the power func
tion
std::cout << "Cube of n is : " <<result<< std::endl;
return 0;
}
Using Classes :
#include <iostream>
using namespace std;
class Sum
{
private: int x, y, z; // private variables
public:
void add()
{
cout<<"Enter two numbers: ";
cin>>x>>y;
z= x+y;
cout<<"Sum of two number is: "<<z<<endl;
}
};
int main()
{
Sum sm;
sm.add();
return 0;
}
- Abstract Class *will atleast have one pure virtual function and can
have data members and method.
- Pure Abstract Class is just like an interface. Only pure virtual
functions can be defined here. No data members or method definition
can be done here.
Example -1
#include <iostream>
#include <string>
using namespace std;
// Interface(Abstract class
// with pure virtual function)
class GFG
{
public:
virtual string returnString() = 0;
};
// Driver code
int main()
{
child childObj;
GFG* ptr;
ptr = &childObj;
cout << ptr->returnString();
return 0;
}
Example -2
class MyInterface
{
public:
// Empty virtual destructor for proper cleanup
virtual ~MyInterface() {}
class MyAbstractClass
{
public:
virtual ~MyAbstractClass();