unit1C++
unit1C++
Unit-I Introduction
1) Objects: Objects are structures that contain both data and procedures. For example, a student is
an object which has name and age,
3) Inheritance: Inheritance is a technique to re-use existing code again and again. Class that is
inherited is called base class and a class which it inherits is called derived class,
4) Polymorphism: Polymorphism means many, which is requesting the same operation to perform
differently,
5) Abstractions: It refers to displaying only essential features of the application and covering the
details,
6) Encapsulation: It means wrapping the data and functions together into a class.
Advantages of OOPs over procedure-oriented programming (POP): With the help of OOPs, it will be
easier for developing and maintaining the software compared to POP. It will be difficult for the
procedure-oriented programming language when the code grows along with the growth of the
project size. Data hiding is enabled in the OOPs whereas the global data could be accessed anywhere
using the procedure-oriented programming language. So this process is risky. Simulating the real
world event effectively is easier with OOPs. Thus, the real-word problem can be solved using this
method. The procedure-oriented programming language is less effective compared to OOPs.
Characteristics of an Object-Oriented Programming Language
Class
C++ Classes/Objects
C++ is an object-oriented programming language.
Everything in C++ is associated with classes and objects, along with its attributes and methods. For
example: in real life, a car is an object. The car has attributes, such as weight and color,
and methods, such as drive and brake.
Attributes and methods are basically variables and functions that belongs to the class. These are
often referred to as "class members".
A class is a user-defined data type that we can use in our program, and it works as an object
constructor, or a "blueprint" for creating objects.
Create a Class
To create a class, use the class keyword:
Example
Create a class called "MyClass":
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
Example explained
The class keyword is used to create a class called MyClass.
The public keyword is an access specifier, which specifies that members (attributes and
methods) of the class are accessible from outside the class. You will learn more about access
specifiers later.
Inside the class, there is an integer variable myNum and a string variable myString. When
variables are declared within a class, they are called attributes.
At last, end the class definition with a semicolon ;
Object
An Object is an identifiable entity with some characteristics and behavior. An Object is an instance of
a Class. When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is
created) memory is allocated.
C++ Object
In C++, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc.
In other words, object is an entity that has state and behavior. Here, state means data and
behavior means functionality.
Object is a runtime entity, it is created at runtime.
Object is an instance of a class. All the members of the class can be accessed through object.
C++
// C++ Program to show the syntax/working of Objects as a
// part of Object Oriented PProgramming
#include <iostream>
using namespace std;
class person {
char name[20];
int id;
public:
void getdetails() {}
};
int main()
{
Encapsulation in C++
Encapsulation also leads to data abstraction or data hiding. Using encapsulation also hides the data.
In the above example, the data of any of the sections like sales, finance, or accounts are hidden from
any other section.
To know more about encapsulation, refer to this article – Encapsulation in C++
Abstraction
Data abstraction is one of the most essential and important features of object-oriented
programming in C++. Abstraction means displaying only essential information and hiding all
unnecessary details. Data abstraction refers to providing only essential information about the data
to the outside world, hiding the background details or implementation. Consider a real-life example
of a man driving a car. The man only knows that pressing the accelerator will increase the speed of
the car or applying brakes will stop the car but he does not know how on pressing the accelerator
the speed is actually increasing, he does not know about the inner mechanism of the car or the
implementation of an accelerator, brakes, etc. in the car. This is what abstraction is.
Abstraction using Classes: We can implement Abstraction in C++ using classes. The class
helps us to group data members and member functions using available access specifiers. A
Class can decide which data member will be visible to the outside world and which is not.
Abstraction in Header files: One more type of abstraction in C++ can be header files. For
example, consider the pow() method present in math.h header file. Whenever we need to
calculate the power of a number, we simply call the function pow() present in the math.h
header file and pass the numbers as arguments without knowing the underlying algorithm
according to which the function is actually calculating the power of numbers.
To know more about C++ abstraction, refer to this article – Abstraction in C++
Polymorphism
C++ Polymorphism
The term "Polymorphism" is the combination of "poly" + "morphs" which means many forms. It is
a greek word. In object-oriented programming, we use 3 main concepts: inheritance,
encapsulation, and polymorphism.
Polymorphism in C++ is a key concept in object-oriented programming (OOP) that describes an
object's ability to have multiple forms or representations. It's a way to reuse and extend code by
allowing the same code to act differently depending on the context.
polymorphism refers to the ability of a C++ function or object to perform in different ways,
depending on how the function or object is used.
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 person at the same time can
have different characteristics. A man at the same time is a father, a husband, and an employee. So
the same person possesses different behavior in different situations. This is called polymorphism. An
operation may exhibit different behaviors in different instances. The behavior depends upon the
types of data used in the operation. C++ supports operator overloading and function overloading.
Operator Overloading: The process of making an operator exhibit different behaviors in
different instances is known as operator overloading.
Function Overloading: Function overloading is using a single function name to perform
different types of tasks. Polymorphism is extensively used in implementing inheritance.
Example: Suppose we have to write a function to add some integers, sometimes there are 2
integers, and sometimes there are 3 integers. We can write the Addition Method with the same
name having different parameters, the concerned method will be called according to parameters.
Polymorphism in C++
To know more about polymorphism, refer to this article – Polymorphism in C++
Inheritance
When properties and member functions of Base class are passed on to the derived class.
The capability of a class to derive properties and characteristics from another class is
called Inheritance. Inheritance is one of the most important features of Object-Oriented
Programming.
Sub Class: The class that inherits properties from another class is called Sub class or Derived
Class.
Super Class: The class whose properties are inherited by a sub-class is called Base Class or
Superclass.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a
new class and there is already a class that includes some of the code that we want, we can
derive our new class from the existing class. By doing this, we are reusing the fields and
methods of the existing class.
Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.
Inheritance in C++
To know more about Inheritance, refer to this article – Inheritance in C++
Dynamic Binding
In dynamic binding, the code to be executed in response to the function call is decided at runtime.
C++ has virtual functions to support this. Because dynamic binding is flexible, it avoids the drawbacks
of static binding, which connected the function call and definition at build time.
Example:
C++
// C++ Program to Demonstrate the Concept of Dynamic Binding without virtual function
#include <iostream>
using namespace std;
class GFG {
public:
void call_Function() // function that calls print
{
print();
}
void print() // the display function
{
cout << "Printing the Base class Content" << endl;
}
};
int main()
{
GFG* geeksforgeeks = new GFG(); // Creating GFG's object using pointer
geeksforgeeks->call_Function(); // Calling call_Function
Output
Printing the Base class Content
Printing the Base class Content
As we can see, the print() function of the parent class is called even from the derived class object. To
resolve this we use virtual functions.
Above Example with virtual Function:
C++
// C++ Program to Demonstrate the Concept of Dynamic binding
// with the help of virtual function
#include <iostream>
using namespace std;
class GFG
{
public:
// using "virtual" for the display function
virtual void print()
{
cout << "Printing the Base class Content" << endl;
}
// function that calls print
void call_Function()
{
print();
}
};
// GFG2 inherits publicly from GFG
class GFG2 : public GFG
{
public:
// GFG2's display
void print() override
{
cout << "Printing the Derived class Content" << endl;
}
};
int main()
{
// Creating GFG's object using pointer
GFG *geeksforgeeks = new GFG();
// Calling call_Function
geeksforgeeks->call_Function();
delete geeksforgeeks;
delete geeksforgeeks2;
return 0;
}
Output
Printing the Base class Content
Printing the Derived class Content
Message Passing
Objects communicate with one another by sending and receiving information. A message for an
object is a request for the execution of a procedure and therefore will invoke a function in the
receiving object that generates the desired results. Message passing involves specifying the name of
the object, the name of the function, and the information to be sent.
Example:
C++
#include <iostream>
using namespace std;
// Define a Car class with a method to display its speed
class Car {
public:
void displaySpeed(int speed) {
cout << "The car is moving at " << speed << " km/h." << endl;
}
};
int main() {
// Create a Car object named myCar
Car myCar;
return 0; }
Advantage of OOPs over Procedure-oriented programming language
Here are key advantages of Object-Oriented Programming (OOP) over Procedure-Oriented
Programming (POP):
1. Modularity and Reusability: OOP promotes modularity through classes and objects,
allowing for code reusability.
2. Data Encapsulation: OOP encapsulates data within objects, enhancing data security and
integrity.
3. Inheritance: OOP supports inheritance, reducing redundancy by reusing existing code.
4. Polymorphism: OOP allows polymorphism, enabling flexible and dynamic code through
method overriding.
5. Abstraction: OOP enables abstraction, hiding complex details and exposing only essential
features
Difference between OOP and POP:
OOP POP
Object functions are linked through Parts of program are linked through
message passing. parameter passing.
use for solving big problems. Not suitable for solving big problems.
C C++
C was developed by Dennis Ritchie between C++ was developed by Bjarne Stroustrup in
the year 1969 and 1973 at AT&T Bell Labs. 1979.
Data and functions are separated in C because Data and functions are encapsulated together
it is a procedural programming language. in form of an object in C++.
Namespace features are not present inside Namespace is used by C++, which avoid name
the C. collisions.
Reference variables are not supported by C. Reference variables are supported by C++.
Virtual and friend functions are not supported Virtual and friend functions are supported by
by C. C++.
C provides malloc() and calloc() functions C++ provides new operator for memory
for dynamic memory allocation, and free() for allocation and delete operator for memory de-
memory de-allocation. allocation.
Class Object
Class does not contain any values which Each object has its own values, which are
can be associated with the field. associated with it.
It is declared using
It is declared using the struct keyword.
2 the class keyword.
Syntax: Syntax:
class class_name { struct structure_name {
data_member; structure_member1;
member_function; structure_member2;
4 }; };
struct structure_name{
type struct_member 1;
class class_name{
type struct_member 2;
data member;
type struct_member 3;
member function;
.
};
type struct_memberN;
Declaration };
Memory
Memory is allocated on the stack. Memory is allocated on the heap.
Allocated
Requires
It may have only parameterized It may have all the types of
constructor and
constructor. constructors and destructors.
destructor