Basics of Object Oriented Programming(OOP)
The major purpose of C++ programming is to introduce the concept of object
orientation to the C programming language. The programming paradigm where
everything is represented as an object is known as truly object-oriented programming
language.
Object means a real word entity such as pen, chair, table etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and
objects. It simplifies the software development and maintenance by providing some
concepts:
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
C++ Classes and Objects
The main purpose of C++ programming is to add object orientation to the C
programming language and classes are the central feature of C++ that supports
object-oriented programming and are often called user-defined types.
A class is used to specify the form of an object and it combines data representation
and methods for manipulating that data into one neat package. The data and
functions within a class are called members of the class.
C++ Class Definitions
When you define a class, you define a blueprint for a data type. This doesn't actually
define any data, but it does define what the class name means, that is, what an object
of the class will consist of and what operations can be performed on such an object.
A class definition starts with the keyword class followed by the class name; and
the class body, enclosed by a pair of curly braces. A class definition must be
followed either by a semicolon or a list of declarations.
• Class Name: The name of the class.
• Access Specifiers: Define the accessibility of members of the class,it control
how members of the class can be accessed:
1. Public:
o Members are accessible from outside the class.
2. Private:
o Members are only accessible within the class.
o Default access specifier if none is specified.
3. Protected:
o Members are accessible within the class and by derived
classes.
• Attributes/Members: Variables that store data about the object,it hold the
state or properties of an object.
Example:
class Car {
public:
string brand;
int speed;
};
• Member Functions: Functions that define the behaviour of the object.
For example,
class Car {
public:
void drive() {
cout << "The car is driving." << endl;
}
};
Define C++ Objects
A class provides the blueprints for objects, so basically an object is created from
a class. We declare objects of a class with exactly the same sort of declaration
that we declare variables of basic types. When a class is defined, only the
specification for the object is defined; no memory or storage is allocated. To use the
data and access functions defined in the class, you need to create objects.
Syntax:
ClassName ObjectName;
Following statements declare two objects of class Box −
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Car c1;
Both of the objects Box1 and Box2 will have their own copy of data members.
Accessing data members and member functions:
The data members and member functions of class can be accessed using the
dot(‘.’) operator with the object.
For example if the name of object is obj and you want to access the member
function with the name printName() then you will have to write obj.printName() .
Accessing the Data Members
The public data members of objects of a class can be accessed using the direct
member access operator (.). The private data members are not allowed to be accessed
directly by the object. Accessing a data member depends solely on the access control
of that data member.
This access control is given by Access modifiers in C++.
There are three access modifiers : public, private and protected.
Let us try the following example to make the things clear −
#include <iostream>
using namespace std;
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
#include <iostream.h>
class Car {
public:
char brand[20]; // Attribute
int speed; // Attribute
void drive() { // Method
cout << brand << " is driving at " << speed << " km/h." << endl;
}
};
int main() {
Car car1; // Create an object
car1.brand = "BMW"; // Assign values to attributes
car1.speed = 150;
car1.drive(); // Call the method
Car car2; // Create an object
Car2.brand = "XYZ"; // Assign values to attributes
Car2.speed = 100;
car2.drive();
return 0;
}
C++ Class Member Functions
A member function of a class is a function that has its definition or its prototype
within the class definition like any other variable. It operates on any object of the
class of which it is a member, and has access to all the members of a class for that
object.
There are 2 ways to define a member function:
• Inside class definition
• Outside class definition
• Inside class definition
In the following example, we define a function inside the class, and we name it
"myMethod".
Note: You access methods just like you access attributes; by creating an object
of the class and using the dot syntax (.):
Inside function 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
myObj.myMethod(); // Call the method
return 0;
}
• Outside class definition
To define a function outside the class definition, you have to declare it inside the
class and then define it outside of the class. This is done by specifiying the name of
the class, followed the scope resolution :: operator, followed by the name of the
function:
Outside function example
To define a function outside the class definition, you have to declare it inside the
class and then define it outside of the class. This is done by specifiying the name of
the class, followed the scope resolution :: operator, followed by the name of the
function:
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;
}
Parameters
You can also add parameters:
#include <iostream.h>
using namespace std;
class Car {
public:
int speed(int maxSpeed);
};
int Car::speed(int maxSpeed) {
return maxSpeed;
}
int main() {
Car myObj; // Create an object of Car
cout << myObj.speed(200); // Call the method with an argument
return 0;
}
The Class Constructor
• A class constructor is a special member function of a class that is executed
whenever we create new objects of that class.
• A constructor will have exact same name as the class.
• It does not have any return type at all, not even void.
• Constructors can be very useful for setting initial values for certain member
variables.
Following example explains the concept of constructor –
#include <iostream.h>
#include <conio.h>
using namespace std;
class hello { // The class
public: // Access specifier
hello () { // Constructor
cout << "Hello World! Program in C++ by using Cons
tructor"; }
void display() {
cout <<"Hello World!" <<endl;
}
};
int main() {
hello myObj; /
return 0;
}
Default Constructor:
A constructor with no parameters or all parameters having default values is called
as Default Constructor. Its automatically initializes objects with default values. If
there is no constructor for a class, the compiler implicitly creates a default
constructor.
#include <iostream>
class MyClass {
public:
int x;
MyClass() { // Default constructor
x = 0;
cout << "Default Constructor Called. x = " << x << endl;
}
};
int main() {
MyClass obj; // Automatically calls the default constructor
return 0;
}
Parameterized Constructor
A default constructor does not have any parameter, but if you need, a constructor can
have parameters. This helps you to assign initial value to an object at the time of its
creation as shown in the following example –
#include <iostream>
class MyClass {
public:
int x;
MyClass(int value) { // Parameterized constructor
x = value;
cout << "Parameterized Constructor Called. x = " << x <<
endl;
}
};
int main() {
MyClass obj(10); // Passes 10 to the parameterized constructor
return 0;
}
Copy Constructor in C++
A copy constructor is a type of constructor that creates an object using another
object of the same class. The process of initializing members of an object
through a copy constructor is known as copy initialization. It is also
called member-wise initialization because the copy constructor initializes one object
with the existing object, both belonging to the same class on a member-by-member
copy basis.
Copy Constructor is of two types:
o Default Copy constructor: The compiler defines the default copy
constructor. If the user defines no copy constructor, compiler supplies its
constructor.
o User Defined constructor: The programmer defines the user-defined
constructor.
Example of Default Constructor
#include <iostream>
class A {
public:
int x;
};
int main() {
// Creating an a1 object
A a1;
a1.x = 10;
cout << "a1's x = " << a1.x << endl;
// Creating another object using a1
// Copy Constructor Calling
A a2(a1);
cout << "a2's x = " << a2.x;
return 0;
}
Output
a1's x = 10
a2's x = 10
In this example, we were able to construct a2 object using already created
object a1.C++ compiler by default create a simple copy constructor when it is not
explicitly defined by the programmer. It is called implicit copy constructor, and it
will copy the bases and members of an object in the same order that they were
present in the code.
C++ also allows programmers to create their own version of copy constructor known
as user defined or explicit copy constructor.
Syntax of User Defined Copy Constructor
Copy constructor takes a reference to an object of the same class as an
argument:
className (const ClassName &obj) {
// Copy logic
……
}
#include <iostream>
class A {
public:
int x;
A(){};
// Copy Constructor definition
A (A& t) {
x = t.x;
cout << "Calling copy constructor" << endl;
}
};
int main() {
// Creating an a1 object
A a1;
a1.x = 10;
cout << "a1's x = " << a1.x << endl;
// Creating another object using a1
// Copy Constructor Calling
A a2(a1);
cout << "a2's x = " << a2.x;
return 0;
}
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 (~).
#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Constructor Invoked"<<endl;
}
~Employee()
{
cout<<"Destructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
return 0;
}
#include<iostream>
using namespace std;
class Demo {
private:
int num1, num2;
public:
Demo(int n1, int n2) {
cout<<"Inside Constructor"<<endl;
num1 = n1;
num2 = n2;
}
void display() {
cout<<"num1 = "<< num1 <<endl;
cout<<"num2 = "<< num2 <<endl;
}
~Demo() {
cout<<"Inside Destructor";
}
};
int main() {
Demo obj1(10, 20);
obj1.display();
return 0;
}
Output
Inside Constructor
num1 = 10
num2 = 20
Inside Destructor
Scope and visibility of variables in function.
Scope, Visibility and Lifetime of variables in C Language are very much
related to each other but still there are some different properties
associated with them that makes them distinct. Scope determines the
region in a C program where a variable is available to use, Visibility
of a variable is related to the accessibility of a variable in a particular
scope of the program and Lifetime of a variable is for how much time a
variable remains in the system's memory.
Scope of Variables in C++
In general, the scope is defined as the extent up to which something can
be worked with. In programming also the scope of a variable is defined
as the extent of the program code within which the variable can be
accessed or declared or worked with.
A scope is a region of the program and broadly speaking there are three
places, where variables can be declared −
• Inside a function or a block which is called local variables,
• In the definition of function parameters which is called formal
parameters.
• Outside of all functions which is called global variables.
We will learn what is a function and it's parameter in subsequent
chapters. Here let us explain what are local and global variables.
Local Variables
Variables that are declared inside a function or block are local variables.
They can be used only by statements that are inside that function or
block of code. Local variables are not known to functions outside their
own.
Variables defined within a function or block are said to be local to
those functions.
• Anything between ‘{‘ and ‘}’ is said to inside a block.
• Local variables do not exist outside the block in which they are
declared, i.e. they can not be accessed or used outside that block.
• Declaring local variables: Local variables are declared inside a
block.
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a, b;
int c;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
}
// CPP program to illustrate usage of local variables
#include<iostream>
void func()
{
// this variable is local to the
// function func() and cannot be
// accessed outside this function
int age=18;
cout<<"Age is: "<<age;
}
int main()
{
cout<<"Age is: "<<age;
return 0;
}
Output:
Error: age was not declared in this scope
Global Variables
Global variables are defined outside of all the functions, usually on top
of the program. The global variables will hold their value throughout the
life-time of your program.
A global variable can be accessed by any function. That is, a global
variable is available for use throughout your entire program after its
declaration.
As the name suggests, Global Variables can be accessed from any part
of the program.
• They are available through out the life time of a program.
• They are declared at the top of the program outside all of the
functions or blocks.
• Declaring global variables: Global variables are usually declared
outside of all of the functions and blocks, at the top of the program.
They can be accessed from any portion of the program.
#include <iostream>
using namespace std;
// Global variable declaration:
int g;
int main () {
// Local variable declaration:
int a, b;
// actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
}
// CPP program to illustrate usage of global variables
#include<iostream>
using namespace std;
// global variable
int global = 5;
// global variable accessed from within a function
void display()
{
cout<<global<<endl;
}
// main function
int main()
{
display();
// changing value of global variable from main function
int global = 10;
display();
}
Output:
5
10
What if there exists a local variable with the
same name as that of global variable inside a
function?
Let us repeat the question once again. The question is : if there is a variable inside
a function with the same name as that of a global variable and if the function tries
to access the variable with that name, then which variable will be given
precedence? Local variable or Global variable?
• Usually when two variable with same name are defined then the
compiler produces a compile time error. But if the variables are
defined in different scopes then the compiler allows it.
• Whenever there is a local variable defined with same name as that
of a global variable then the compiler will give precedence to the
local variable
// CPP program to illustrate scope of local variables and global
variables together
#include<iostream>
using namespace std;
// global variable
int global = 5;
// main function
int main()
{ cout << global << endl;
// local variable with same
// name as that of global variable
int global = 2;
cout << global << endl;
}
#include <iostream>
using namespace std;
// Global variable declaration:
int g = 20;
int main () {
// Local variable declaration:
int g = 10;
cout << g;
return 0;
}
When the above code is compiled and executed, it produces the following
result −
10
Initializing Local and Global Variables
When a local variable is defined, it is not initialized by the system, you
must initialize it yourself. Global variables are initialized automatically
by the system when you define them as follows −
Data Type Initializer
Int 0
Char '\0'
Float 0
Double 0
Pointer NULL
It is a good programming practice to initialize variables properly,
otherwise sometimes program would produce unexpected result.
Scope resolution operator in C++
In C++, scope resolution operator is ::. It is used for following purposes.
1) To access a global variable when there is a local variable
with same name:
// C++ program to show that we can access a global variable
// using scope resolution operator :: when there is a local
// variable with same name
#include<iostream>
int x; // Global x
int main()
{
int x = 10; // Local x
cout << "Value of global x is " << ::x;
cout << "\nValue of local x is " << x;
return 0;
}
Output:
Value of global x is 0
Value of local x is 10
2) To define a function outside a class.
// C++ program to show that scope resolution operator :: is used
// to define a function outside a class
#include<iostream>
class A
{
public:
// Only declaration
void fun();
};
// Definition outside class using ::
void A::fun()
{
cout << "fun() called";
}
int main()
{
A a;
a.fun();
return 0;
}
Output:
fun() called
3) To access a class’s static variables.
// C++ program to show that :: can be used to access static
// members when there is a local variable with same name
#include<iostream>
class Test
{
static int x;
public:
static int y;
// Local parameter 'a' hides class member
// 'a', but we can access it using ::
void func(int x)
{
// We can access class's static variable
// even if there is a local variable
cout << "Value of static x is " << Test::x;
cout << "\nValue of local x is " << x;
}
};
// In C++, static members must be explicitly defined
// like this
int Test::x = 1;
int Test::y = 2;
int main()
{
Test obj;
int x = 3 ;
obj.func(x);
cout << "\nTest::y = " << Test::y;
return 0;
}
Output:
Value of static x is 1
Value of local x is 3
Test::y = 2;
4) In case of multiple Inheritance:
If same variable name exists in two ancestor classes, we can use scope
resolution operator to distinguish.
// Use of scope resolution operator in multiple inheritance.
#include<iostream>
class A
{
protected:
int x;
public:
A() {
x = 10;
}
};
class B
{
protected:
int x;
public:
B() { x = 20; }
};
class C: public A, public B
{
public:
void fun()
{
cout << "A's x is " << A::x;
cout << "\nB's x is " << B::x;
}
};
int main()
{
C c;
c.fun();
return 0;
}
Output:
A's x is 10
B's x is 20
5) For namespace
If a class having the same name exists inside two namespace we can use the
namespace name with the scope resolution operator to refer that class without
any conflicts
// Use of scope resolution operator for namespace.
#include<iostream>
int main(){
std::cout << "Hello" << std::endl;
Here, cout and endl belong to the std namespace.
Friend Class and Friend Functions in C++
As we know that a class cannot access the private members of other
class. Similarly a class that doesn’t inherit another class cannot access its
protected members.
Friend Class:
A friend class is a class that can access the private and protected
members of a class in which it is declared as friend. This is needed
when we want to allow a particular class to access the private and
protected members of a class.
#include <iostream>
using namespace std;
class XYZ {
private:
char ch='A';
int num = 11;
public:
/* This statement would make class ABC
* a friend class of XYZ, this means that
* ABC can access the private and protected
* members of XYZ class.
*/
friend class ABC;
};
class ABC {
public:
void disp(XYZ obj){
cout<<obj.ch<<endl;
cout<<obj.num<<endl;
}
};
int main() {
ABC obj;
XYZ obj2;
obj.disp(obj2);
return 0;
}
Output:
A
11
Friend Function
Like friend class, a friend function can be given a special grant to access
private and protected members. A friend function can be:
a) A member of another class
b) A global function
#include <iostream>
using namespace std;
class XYZ {
private:
int num=100;
char ch='Z';
public:
friend void disp(XYZ obj);
};
//Global Function
void disp(XYZ obj){
cout<<obj.num<<endl;
cout<<obj.ch<<endl;
}
int main() {
XYZ obj;
disp(obj);
return 0;
}
Output:
100
Z
#include <iostream>
class Box {
double width;
public:
friend void printWidth( Box box );
void setWidth( double wid );
};
// Member function definition
void Box::setWidth( double wid ) {
width = wid;
}
// Note: printWidth() is not a member function of any class.
void printWidth( Box box ) {
/* Because printWidth() is a friend of Box, it can
directly access any member of this class */
cout << "Width of box : " << box.width <<endl;
}
// Main function for the program
int main() {
Box box;
// set box width without member function
box.setWidth(10.0);
// Use friend function to print the wdith.
printWidth( box );
return 0;
}
When the above code is compiled and executed, it produces the
following result −
Width of box : 10
Following are some important points about friend functions and
classes:
1) Friends should be used only for limited purpose. too many functions
or external classes are declared as friends of a class with protected or
private data, it lessens the value of encapsulation of separate classes in
object-oriented programming.
2) Friendship is not mutual. If class A is a friend of B, then B doesn’t
become a friend of A automatically.
3) Friendship is not inherited.
4) The concept of friends is not there in Java.