Basic Concepts of Object-oriented Programming
1. Class
A class is a user defined data type. A class is a logical abstraction. It is a template that defines
the form of an object. A class specifies both code and data. It is not until an object of that class
has been created that a physical representation of that class exists in memory. When you define
a class, you declare the data that it contains and the code that operates on that data. Data is
contained in instance variables defined by the class known as data members, and code is
contained in functions known as member functions. The code and data that constitute a class are
called members of the class.
2. Object
An object is an identifiable entity with specific characteristics and behavior. An object is said
to be an instance of a class. Defining an object is similar to defining a variable of any data
type. Space is set aside for it in memory.
3. Encapsulation
Encapsulation is a programming mechanism that binds together code and the data it
manipulates, and that keeps both safe from outside interference and misuse. C++’s basic unit
of encapsulation is the class. Within a class, code or data or both may be private to that object
or public. Private code or data is known to and accessible by only another part of the object.
That is, private code or data cannot be accessed by a piece of the program that exists outside
the object. When code or data is public, other parts of your program can access it even though
it is defined within an object. Typically, the public parts of an object are used to provide a
controlled interface to the private elements of the object. This insulation of the data from
direct access by the program is called data hiding
4. Data abstraction
In object oriented programming, each object will have external interfaces through which it
can be made use of. There is no need to look into its inner details. The object itself may be
made of many smaller objects again with proper interfaces. The user needs to know the
external interfaces only to make use of an object. The internal details of the objects are
hidden which makes them abstract. The technique of hiding internal details in an object is
called data abstraction.
5. Inheritance
Inheritance is the mechanism by which one class can inherit the properties of another. It allows
a hierarchy of classes to be build, moving from the most general to the most specific. When
one class is inherited by another, the class that is inherited is called the base class. The
inheriting class is called the derived class. In general, the process of inheritance begins with
the definition of a base class. The base class defines all qualities that will be common to any
derived class. . In OOPs, the concept of inheritance provides the idea of reusability .
PRIYANKA SONI
6. Polymorphism
Polymorphism (from the Greek, meaning “many forms”) is a feature that allows one interface
to be used for a general class of actions. The specific action is determined by the exact nature
of the situation. The concept of polymorphism is often expressed by the phrase “one interface,
multiple methods.” This means that it is possible to design a generic interface to a group of
related activities. This helps reduce complexity by allowing the same interface to be used to
specify a general class of action. It is the compiler’s job to select the specific action as it applies
to each situation.
Applications of C++ Programming
As mentioned before, C++ is one of the most widely used programming languages. It has it's
presence in almost every area of software development. I'm going to list few of them here:
Application Software Development - C++ programming has been used in
developing almost all the major Operating Systems like Windows, Mac OSX and
Linux. Apart from the operating systems, the core part of many browsers like Mozilla
Firefox and Chrome have been written using C++. C++ also has been used in
developing the most popular database system called MySQL.
Programming Languages Development - C++ has been used extensively in
developing new programming languages like C#, Java, JavaScript, Perl, UNIX’s C
Shell, PHP and Python, and Verilog etc.
Computation Programming - C++ is the best friends of scientists because of fast
speed and computational efficiencies.
Games Development - C++ is extremely fast which allows programmers to do
procedural programming for CPU intensive functions and provides greater control
over hardware, because of which it has been widely used in development of gaming
engines.
Embedded System - C++ is being heavily used in developing Medical and
Engineering Applications like softwares for MRI machines, high-end CAD/CAM
systems etc.
This list goes on, there are various areas where software developers are happily using C++ to
provide great softwares. I highly recommend you to learn C++ and contribute great softwares
to the community.
Benefits of OOPS:
1. Modularity for easier troubleshooting
2. Reuse of code through inheritance
3. Flexibility through polymorphism
4. Effective problem solving
PRIYANKA SONI
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
Class
Collection of objects is called class. It is a logical entity.
Classes and objects are the two main aspects of object-oriented programming.
Look at the following illustration to see the difference between class and objects:
Class
Fruit
Objects
Apple, Banana Mango
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)
};
Create an Object
In C++, an object is created from a class. We have already created the class named MyClass, so
now we can use this to create objects.
class MyClass
{ // The class
public: // Access specifier
PRIYANKA SONI
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
int main()
MyClass myObj; // Create an object of MyClass
// Access attributes and set values
myObj.myNum = 15;
myObj.myString = "Some text"; // Print attribute values
cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
C++ Class Methods
Methods are functions that belongs to the class.
There are two ways to define functions that belongs to a class:
Inside class definition
Outside class definition
Inside Example
class MyClass
{ // The class
public: // Access specifier
void myMethod()
{ // Method/function defined inside the class
cout << "Hello World!";
}
};
int main()
{ MyClass myObj; // Create an object of MyClass
PRIYANKA SONI
myObj.myMethod(); // Call the method
return 0;
Outside Example
class MyClass
{ // The class
public: // Access specifier
void myMethod(); // Method/function declaration
};
// Method/function definition outside the class
void MyClass::myMethod()
cout << "Hello World!";
}
int main()
{
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
C++ Constructors
A constructor in C++ is a special method that is automatically called when an object of a
class is created.
To create a constructor, use the same name as the class, followed by parentheses ():
There can be two types of constructors in C++.
Default constructor
Parameterized constructor
Example:
1. #include <iostream>
3. class Employee
PRIYANKA SONI
4. {
5. public:
6. Employee()
7. {
8. cout<<"Default Constructor Invoked"<<endl;
9. }
10. };
11. int main(void)
12. {
13. Employee e1; //creating an object of Employee
14. Employee e2;
15. return 0;
16. }
OUTPUT:
Default Constructor Invoked
Default Constructor Invoked
C++ Parameterized Constructor
A constructor which has parameters is called parameterized constructor. It is used to provide
different values to distinct objects.
Let's see the simple example of C++ Parameterized Constructor.
#include <iostream>
using namespace std;
class Employee {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
Employee(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
PRIYANKA SONI
int main(void)
{
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee
Employee e2=Employee(102, "Nakul", 59000);
e1.display();
e2.display();
return 0;
}
Output:
101 Sonoo 890000
102 Nakul 59000
C++ Destructor
A destructor works opposite to constructor; it destructs the objects of classes. It can be
defined only once in a class. Like constructors, it is invoked automatically.
A destructor is defined like constructor. It must have same name as class. But it is prefixed
with a tilde sign (~).
Example:
1. #include <iostream>
2. using namespace std;
3. class Employee
4. {
5. public:
6. Employee()
7. {
8. cout<<"Constructor Invoked"<<endl;
9. }
10. ~Employee()
11. {
12. cout<<"Destructor Invoked"<<endl;
13. }
14. };
15. int main(void)
16. {
17. Employee e1; //creating an object of Employee
18. Employee e2; //creating an object of Employee
19. return 0;
20. }
PRIYANKA SONI
Output:
Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked
C++ Friend function
If a function is defined as a friend function in C++, then the protected and private data of a
class can be accessed using the function.
By using the keyword friend compiler knows the given function is a friend function.
For accessing the data, the declaration of a friend function should be done inside the body of
a class starting with the keyword friend
Declaration of friend function in C++
1. class class_name
2. {
3. friend data_type function_name(argument/s); // syntax of friend function.
4. };
Characteristics of a Friend function:
The function is not in the scope of the class to which it has been declared as a friend.
It cannot be called using the object as it is not in the scope of that class.
It can be invoked like a normal function without using the object.
It cannot access the member names directly and has to use an object name and dot
membership operator with the member’s name.
It can be declared either in the private or the public part.
C++ Polymorphism
The term "Polymorphism" is the combination of "poly" + "morphs" which means many
forms.
There are two types of polymorphism in C++
PRIYANKA SONI
Compile time polymorphism:
The overloaded functions are invoked by matching the type and number of arguments. This
information is available at the compile time and, therefore, compiler selects the appropriate
function at the compile time. It is achieved by function overloading and operator overloading
which is also known as static binding or early binding.
Example of Function Overloading:
#include <iostream>
using namespace std;
class printData
{
public:
void print(int i)
{
cout << "Printing int: " << i << endl;
}
void print(double f)
{
cout << "Printing float: " << f << endl;
}
void print(char* c)
{
cout << "Printing character: " << c << endl;
}
};
int main(void)
{
printData pd;
// Call print to print integer
pd.print(5);
// Call print to print float
PRIYANKA SONI
pd.print(500.263);
// Call print to print character
pd.print("Hello C++");
return 0;
}
Output:
Printing int: 5
Printing float: 500.263
Printing character: Hello C++
Run time polymorphism:
Run time polymorphism is achieved when the object's method is invoked at the run time instead
of compile time. It is achieved by method overriding which is also known as dynamic binding or
late binding.
Example:
1. #include <iostream>
2. using namespace std;
3. class Animal {
4. public:
5. void eat(){
6. cout<<"Eating...";
7. }
8. };
9. class Dog: public Animal
10. {
11. public:
12. void eat()
13. { cout<<"Eating bread...";
14. }
15. };
16. int main(void) {
17. Dog d = Dog();
18. d.eat();
19. return 0;
20. }
Output:
Eating bread...
PRIYANKA SONI
Differences b/w Compile time and Run time Run time polymorphism or Overriding
Polymorphism. Compile time polymorphism
The function to be invoked is known at the The function to be invoked is known at the run
compile time. time.
It is also known as overloading, early binding It is also known as overriding, Dynamic
and static binding. binding and late binding.
Overloading is a compile time polymorphism Overriding is a run time polymorphism where
where more than one method is having the more than one method is having the same
same name but with the different number of name, number of parameters and the type of the
parameters or the type of the parameters. parameters.
It is achieved by function overloading and It is achieved by virtual functions and pointers.
operator overloading.
It provides fast execution as it is known at the It provides slow execution as it is known at the
compile time. run time.
It is less flexible as mainly all the things It is more flexible as all the things execute at
execute at the compile time. the run time.
C++ Reference Variable
A reference variable is an alias, that is, another name for an already existing variable. Once a
reference is initialized with a variable, either the variable name or the reference name may be
used to refer to the variable
References vs Pointers
References are often confused with pointers but three major differences between references and
pointers are −
1) You cannot have NULL references. You must always be able to assume that a reference is
connected to a legitimate piece of storage.
2) Once a reference is initialized to an object, it cannot be changed to refer to another object.
Pointers can be pointed to another object at any time.
3) A reference must be initialized when it is created. Pointers can be initialized at any time.
Creating References in C++
Think of a variable name as a label attached to the variable's location in memory. You can then
think of a reference as a second label attached to that memory location. Therefore, you can
access the contents of the variable through either the original variable name or the reference.
For example, suppose we have the following example −
int i = 17;
PRIYANKA SONI
We can declare reference variables for i as follows.
int& r = i;
Read the & in these declarations as reference. Thus, read the first declaration as "r is an integer
reference initialized to i" and read the second declaration as "s is a double reference initialized
to d.". Following example makes use of references on int and double –
#include <iostream>
using namespace std;
int main () {
// declare simple variables
int i;
double d;
// declare reference variables
int& r = i;
double& s = d;
i = 5;
cout << "Value of i : " << i << endl;
cout << "Value of i reference : " << r << endl;
d = 11.7;
cout << "Value of d : " << d << endl;
cout << "Value of d reference : " << s << endl;
return 0;
}
Output:
Value of i : 5
Value of i reference : 5
Value of d : 11.7
Value of d reference : 11.7
PRIYANKA SONI