0% found this document useful (0 votes)
17 views21 pages

OOPc++ Standard

Uploaded by

cvekariya16
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views21 pages

OOPc++ Standard

Uploaded by

cvekariya16
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

OOPC++

Overview
1) What is OOP ?

Object-oriented programming (OOP) is a computer programming model that organizes software


design around data, or objects, rather than functions and logic. An object can be defined as a data
field that has unique attributes and behavior.

2) How OOP is related to real world ?

There are 4 OOP concepts. They are,

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

1. Members of a structure are


1. Members of a class are private by default.
public by default.

2. An instance of structure is called


2. An instance of a class is called an ‘object’.
the ‘structure variable’.
Class Structure

3. Member classes/structures of a class are private by


3. Member classes/structures of a
default but not all programming languages have this
structure are public by default.
default behavior eg Java etc.

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:

class class_name{ struct structure_name{

data_member; type structure_member1;

member_function; type structure_member2;

}; };

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.

In C++, there are 3 access modifiers:

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;
}

Enter your age: 20


Age = 20

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;
};

// declare child class


class SampleChild : public Sample {
public:
void displayAge(int a) {
age = a;
cout << "Age = " << age << endl;
}
};

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;
}

Enter your age: 20


Age = 20
Specifiers Same Class Derived Class Outside Class

public Yes Yes Yes

private Yes No No

protected Yes Yes No

3) Types of Class Member Functions in C++ –

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;
}
};

// initialize the static data members


int Box :: length = 10;
int Box :: breadth = 20;
int Box :: height = 30;

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

-The compiler may not perform inlining in such circumstances as:

If a function contains a loop. (for, while and do-while)

If a function contains static variables.

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.

If a function contains a switch or goto statement.

#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;
}

2)Parameterized Constructor - Parameterized Constructors make it possible to pass arguments to


constructors.

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

No. Object Class

1) Object is an instance of a class. Class is a blueprint or template from


which objects are created.

2) Object is a real world entity such as pen, Class is a group of similar objects.
laptop, mobile, bed, keyboard, mouse, chair
etc.

3) Object is a physical entity. Class is a logical entity.

4) Object is created through new Class is declared using class


keyword mainly e.g. keyword e.g.
Student s1=new Student(); class Student{}

5) Object is created many times as per Class is declared once.


requirement.
6) Object allocates memory when it is Class doesn't allocated memory when
created. it is created.

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:

Class: Human Object: Man, Woman

Class: Fruit Object: Apple, Banana, Mango, Guava wtc.

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.

Compile-time Polymorphism - This type of polymorphism is achieved by function


overloading or operator overloading.

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;
}

// Function with same name but


// 1 double parameter
void func(double x)
{
cout << "value of x is " << x << endl;
}

// Function with same name and


// 2 int parameters
void func(int x, int y)
{
cout << "value of x and y is " << x << ", " << y
<< endl;
}
};

// Driver code
int main()
{
Geeks obj1;

// Function being called depends


// on the parameters passed
// func() is called with int value
obj1.func(7);

// func() is called with double value


obj1.func(9.132);

// func() is called with 2 int values


obj1.func(85, 64);
return 0;
}

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;
}

// This is automatically called


// when '+' is used with between
// two Complex objects
Complex operator +(Complex const & obj)
{
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << endl; }
};

// Driver code
int main()
{
Complex c1(10, 5), c2(2, 4);

// An example call to "operator+"


Complex c3 = c1 + c2;
c3.print();
}
Runtime Polymorphism - This type of polymorphism is achieved by Function
Overriding.

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;
}
};

class Rectangle : public Shape {


public:
void draw() {
cout << "drawing rectangle..." << endl;
}
};

class Circle : public Shape {


public:
void draw() {
cout << "drawing circle..." << endl;
}
};

class Triangle : public Shape {


public:
void draw() {
cout << "drawing triangle..." << 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;
}
};

class Rectangle : public Shape {


public:
void draw() {
cout << "drawing rectangle..." << endl;
}
};

class Circle : public Shape {


public:
void draw() {
cout << "drawing circle..." << endl;
}
};

class Triangle : public Shape {


public:
void draw() {
cout << "drawing triangle..." << 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";
}
};

class B: public virtual A {


};

class C: public virtual A {


};

class D: public B, public C {


};

int main() {
D object; // Object creation of class D.

return 0;
}

Output:-
Constructor A

4) What is an abstract class

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;

cout << "Enter the length of the square: ";


square.getDimension();
cout << "Area of square: " << square.calculateArea() << endl;

cout << "\nEnter radius of the circle: ";


circle.getDimension();
cout << "Area of circle: " << circle.calculateArea() << endl;

return 0;
}

Inheritance
Inheritance in Java is a mechanism in which one object acquires all the properties
and behaviors of a parent object.

Note:

 In C++, the default mode of visibility is private.


 The private members of the base class are never inherited.
C++ supports five types of inheritance:

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

Encapsulation can also be defined in two different ways:

1) Data hiding: Encapsulation is the process of hiding unwanted information,


such as restricting access to any member of an object. Using Access
Specifier(public, private, protected).

2) Data binding: Encapsulation is the process of binding the data members and
the methods together as a whole, as a class.

Encapsulation is the combination of Data hiding and Abstraction

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
}

2) How Encapsulation is achieved in a class?

 Make all the data members private.


 Create public setter and getter functions for each data member in such a
way that the set function set the value of data member and get function
get the value of data member.

Abstraction
Data Abstraction is a process of providing only the essential details to the
outside world and hiding the internal details

How to achieve :

 C++ --> Access specifiers and header files


 JAVA --> Interfaces and Abstract classes

1)Data Abstraction can be achieved in two ways in C++:

1) Abstraction using classes : An abstraction can be achieved using classes.


A class is used to group all the data members and member functions into
a single unit by using the access specifiers. A class has the responsibility
to determine which data member is to be visible outside and which is not.
2) Abstraction in header files : An another type of abstraction is header file.
For example, pow() function available is used to calculate the power of a
number without actually knowing which algorithm function uses to
calculate the power. Thus, we can say that header files hides all the
implementation details from the user.

Using header files :

#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;
}

2)Advantages of Data Abstraction :

 Helps the user to avoid writing the low-level code


 Avoids code duplication and increases reusability.
 Can change the internal implementation of the class independently
without affecting the user.
 Helps to increase the security of an application or program as only
important details are provided to the user.
 It reduces the complexity as well as the redundancy of the code, therefore
increasing the readability

3)C++ Program to Create an Interface :

In C++ programming there is no built-in concept of interfaces. In order to create


an interface, we need to create an abstract class which is having only pure
virtual methods. In C++, Interfaces are also called pure abstract classes.

Pure Virtual Functions

 A Pure Virtual Function is a function where we only declare the function


but not the function definition. The implementation for pure virtual
methods is done at the derived class by method/function overriding.
 virtual datatype functionName(parameter1, parameter2,…) = 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.

Rules While Using Interfaces

- Declare only pure virtual functions. (No definition)


- For pure virtual functions assign only 0.
- Cannot create an instance of the class.
- We can create a pointer to the instance of the derived class with a
reference of a base abstract class.

Example -1

#include <iostream>
#include <string>
using namespace std;

// Interface(Abstract class
// with pure virtual function)
class GFG
{
public:
virtual string returnString() = 0;
};

class child : public GFG


{
public:
string returnString()
{
return "GeeksforGeeks";
}
};

// 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() {}

virtual void Method1() = 0;


virtual void Method2() = 0;
};

class MyAbstractClass
{
public:
virtual ~MyAbstractClass();

virtual void Method1();


virtual void Method2();
void Method3();

virtual void Method4() = 0; // make MyAbstractClass not instantiable


};

You might also like