Sunteți pe pagina 1din 23

Object Oriented Programming

Object Oriented programming is a programming style that is associated with the concept of Class,
Objects and various other concepts revolving around these two, like Inheritance, Polymorphism,
Abstraction, Encapsulation etc.

Class
Here we can take Human Being as a class. A class is a blueprint for any functional entity which
defines its properties and its functions. Like Human Being, having body parts, and performing
various actions.

Inheritance
Considering HumanBeing a class, which has properties like hands, legs, eyes etc, and functions like
walk, talk, eat, see etc. Male and Female are also classes, but most of the properties and functions
are included in HumanBeing, hence they can inherit everything from class HumanBeing using the
concept of Inheritance.

Objects
My name is Abhishek, and I am an instance/object of class Male. When we say, Human Being,
Male or Female, we just mean a kind, you, your friend, me we are the forms of these classes. We
have a physical existence while a class is just a logical definition. We are the objects.
Abstraction
Abstraction means, showcasing only the required things to the outside world while hiding the details.
Continuing our example, Human Being's can talk, walk, hear, eat, but the details are hidden from
the outside world. We can take our skin as the Abstraction factor in our case, hiding the inside
mechanism.

Encapsulation
This concept is a little tricky to explain with our example. Our Legs are binded to help us walk. Our
hands, help us hold things. This binding of the properties to functions is called Encapsulation.

Polymorphism
Polymorphism is a concept, which allows us to redefine the way something works, by either
changing how it is done or by changing the parts using which it is done. Both the ways have different
terms for them.
If we walk using our hands, and not legs, here we will change the parts used to perform something.
Hence this is called Overloading.
And if there is a defined way of walking, but I wish to walk differently, but using my legs, like
everyone else. Then I can walk like I want, this will be called as Overriding.

OOPS Concept Definitions


Now, let us discuss some of the main features of Object Oriented Programming which you will be
using in C++(technically).

1. Objects
2. Classes
3. Abstraction
4. Encapsulation
5. Inheritance
6. Overloading
7. Exception Handling
Objects
Objects are the basic unit of OOP. They are instances of class, which have data members and uses
various member functions to perform tasks.

Class
It is similar to structures in C language. Class can also be defined as user defined data type but it
also contains functions in it. So, class is basically a blueprint for object. It declare & defines what
data variables the object will have and what operations can be performed on the class's object.

Abstraction
Abstraction refers to showing only the essential features of the application and hiding the details. In
C++, classes can provide methods to the outside world to access & use the data variables, keeping
the variables hidden from direct access, or classes can even declare everything accessible to
everyone, or maybe just to the classes inheriting it. This can be done using access specifiers.

Encapsulation
It can also be said data binding. Encapsulation is all about binding the data variables and functions
together in class.

Inheritance
Inheritance is a way to reuse once written code again and again. The class which is inherited is
called the Base class & the class which inherits is called the Derived class. They are also called
parent and child class.
So when, a derived class inherits a base class, the derived class can use all the functions which are
defined in base class, hence making code reusable.

Polymorphism
It is a feature, which lets us create functions with same name but different arguments, which will
perform different actions. That means, functions with same name, but functioning in different ways.
Or, it also allows us to redefine a function to provide it with a completely new definition. You will
learn how to do this in details soon in coming lessons.

Exception Handling
Exception handling is a feature of OOP, to handle unresolved exceptions or errors produced at
runtime.
First C++ program
#include <iostream.h>

using namespace std;

int main()

cout << "Hello this is C++";

Header files are included at the beginning just like in C program. Here iostream is a header file
which provides us with input & output streams. Header files contained predeclared function libraries,
which can be used by users for their ease.
Using namespace std, tells the compiler to use standard namespace. Namespace collects
identifiers used for class, object and variables. NameSpace can be used by two ways in a program,
either by the use of using statement at the beginning, like we did in above mentioned program or by
using name of namespace as prefix before the identifier with scope resolution (::) operator.
Example : std::cout << "A";
main(), is the function which holds the executing part of program its return type is int.
cout <<, is used to print anything on screen, same as printf in C language. cin and cout are same
as scanf and printf, only difference is that you do not need to mention format specifiers like, %d for
int etc, in cout & cin.

C++ Class Definitions


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.
For example, we defined the Box data type using the keyword class as
follows −
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
The keyword public determines the access attributes of the members of
the class that follows it. A public member can be accessed from outside the
class anywhere within the scope of the class object. You can also specify
the members of a class as private or protected which we will discuss in a
sub-section.

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.
Following statements declare two objects of class Box −
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box

Both of the objects Box1 and Box2 will have their own copy of data
members.

A class describes both the properties (data) and behaviors (functions) of objects. Classes are
not objects, but they are used to instantiate objects.

What is a class?
 A class is an abstract data type similar to 'C structure'.
 The Class representation of objects and the sets of operations that can be applied to such
objects.
 The class consists of Data members and methods.

The primary purpose of a class is to hold data/information. This is achieved with attributes which
are also known as data members.

The member functions determine the behavior of the class i.e. provide a definition for supporting
various operations on data held in form of an object.

Definition of a class
Syntax:

Class class_name

{
Data Members;

Methods;

Example:

class A

public:

double length; // Length of a box

double breadth; // Breadth of a box

double height; // Height of a box

 Private, Protected, Public is called visibility labels.


 The members that are declared private can be accessed only from within the class.
 Public members can be accessed from outside the class also.
 In C++, data can be hidden by making it private.

Access Control in Classes


Now before studying how to define class and its objects, lets first quickly learn what are access
specifiers.
Access specifiers in C++ class defines the access control rules. C++ has 3 new keywords
introduced, namely,

1. public
2. private
3. protected

These access specifiers are used to set boundaries for availability of members of class be it data
members or member functions
Access specifiers in the program, are followed by a colon. You can use either one, two or all 3
specifiers in the same class to set different boundaries for different class members. They change the
boundary for all the declarations that follow them.
Public
Public, means all the class members declared under public will be available to everyone. The data
members and member functions declared public can be accessed by other classes too. Hence there
are chances that they might change them. So the key members must not be declared public.
class PublicAccess

public: // public access specifier

int x; // Data Member Declaration

void display(); // Member Function decaration

Private
Private keyword, means that no one can access the class members declared private outside that
class. If someone tries to access the private member, they will get a compile time error. By default
class variables and member functions are private.
class PrivateAccess

private: // private access specifier

int x; // Data Member Declaration

void display(); // Member Function decaration

Protected
Protected, is the last access specifier, and it is similar to private, it makes class member inaccessible
outside the class. But they can be accessed by any subclass of that class. (If class A is inherited by
class B, then class B is subclass of class A. We will learn this later.)
class ProtectedAccess

protected: // protected access specifier

int x; // Data Member Declaration

void display(); // Member Function decaration

Data Members
Data and functions are members.
Data Members and methods must be declared within the class definition.

Example:

Class A

int i; // i is a data member of class A

int j; // j is a data member of class A

int i; // Error redefinition of i

 A member cannot be redeclared within a class.


 No member can be added elsewhere other than in the class definition.
Example:
Class A

int i;

int j;

void f (int, int);

int g();

f and g are a member function of class A. They determine the behavior of the objects of class
A.

Accessing the Data Members


The public data members of objects of a class can be accessed using the direct member access
operator (.).

Let us try the following example to make the things clear:


Example:

#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 = 4.0;

Box1.length = 6.0;

Box1.breadth = 3.0;

// box 2 specification

Box2.height = 10.0;

Box2.length = 12.0;
Box2.breadth = 12.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;

Program Output:

It is important to note that private and protected members cannot be accessed directly using
direct member access operator (.). We will learn how private and protected members can be
accessed.

Program to Enter Students Details and Display it


Example:

#include <iostream>

using namespace std;


class stud

public:

char name[30],clas[10];

int rol,age;

void enter()

cout<<"Enter Student Name: "; cin>>name;

cout<<"Enter Student Age: "; cin>>age;

cout<<"Enter Student Roll number: "; cin>>rol;

cout<<"Enter Student Class: "; cin>>clas;

void display()

cout<<"\n Age\tName\tR.No.\tClass";

cout<<"\n"<<age<<"\t"<<name<<"\t"<<rol<<"\t"<<clas;

};

int main()

class stud s;

s.enter();
s.display();

cin.get();//use this to wait for a keypress

Program Output:

Accessing Data Members of Class


Accessing a data member depends solely on the access control of that data member. If its public,
then the data member can be easily accessed using the direct member access (.) operator with the
object of that class.
If, the data member is defined as private or protected, then we cannot access the data variables
directly. Then we will have to create special public member functions to access, use or initialize the
private and protected data members. These member functions are also
called Accessors and Mutator methods or getter and setter functions.

Accessing Public Data Members


Following is an example to show you how to initialize and use the public data members using the dot
(.) operator and the respective object of class.
class Student

public:

int rollno;

string name;

};

int main()

Student A;

Student B;

A.rollno=1;
A.name="Adam";

B.rollno=2;

B.name="Bella";

cout <<"Name and Roll no of A is :"<< A.name << A.rollno;

cout <<"Name and Roll no of B is :"<< B.name << B.rollno;

Accessing Private Data Members


To access, use and initialize the private data member you need to create getter and setter functions,
to get and set the value of the data member.
The setter function will set the value passed as argument to the private data member, and the getter
function will return the value of the private data member to be used. Both getter and setter function
must be defined public.
Example :
class Student

private: // private data member

int rollno;

public: // public accessor and mutator functions

int getRollno()

return rollno;

void setRollno(int i)

rollno=i;

};

int main()

Student A;

A.rollono=1; //Compile time error

cout<< A.rollno; //Compile time error


A.setRollno(1); //Rollno initialized to 1

cout<< A.getRollno(); //Output will be 1

So this is how we access and use the private data members of any class using the getter and setter
methods. We will discuss this in more details later.

Accessing Protected Data Members


Protected data members, can be accessed directly using dot (.) operator inside the subclass of the
current class, for non-subclass we will have to follow the steps same as to access private data
member.

Types of Member Functions


We already know what member functions are and what they do. Now lets study some special
member functins present in the class. Following are different types of Member functions,

1. Simple functions
2. Static functions
3. Const functions
4. Inline functions
5. Friend functions

Simple Member functions


These are the basic member function, which dont have any special keyword like static etc as prefix.
All the general member functions, which are of below given form, are termed as simple and basic
member functions.
return_type functionName(parameter_list)

function body;

Static Member functions


Static is something that holds its position. Static is a keyword which can be used with data members
as well as the member functions. We will discuss this in details later. As of now we will discuss its
usage with member functions only.
A function is made static by using static keyword with function name. These functions work for the
class as whole rather than for a particular object of a class.
It can be called using the object and the direct member access . operator. But, its more typical to
call a static member function by itself, using class name and scope resolution :: operator.
Example :
class X

public:

static void f(){};

};

int main()

X::f(); // calling member function directly with class name

These functions cannot access ordinary data members and member functions, but only static data
members and static member functions.
It doesn't have any "this" keyword which is the reason it cannot access ordinary members. We will
study about "this" keyword later.

Const Member functions


We will study Const keyword in detail later, but as an introduction, Const keyword makes variables
constant, that means once defined, there values can't be changed.
When used with member function, such member functions can never modify the object or its related
data members.
//Basic Syntax of const Member Function

void fun() const {}

Inline functions
All the member functions defined inside the class definition are by default declared as Inline.

Inline Functions in C++


All the member functions defined inside the class definition are by default declared as Inline. Let us
have some background knowledge about these functions.
You must remember Preprocessors from C language. Inline functions in C++ do the same thing what
Macros do in C. Preprocessors were not used in C++ because they had some drawbacks.
Drawbacks of Macro
In Macro, we define certain variable with its value at the beginning of the program, and everywhere
inside the program where we use that variable, its replaced by its value on Compilation.

1) Problem with spacing


Let us see this problem using an example,
#define G (y) (y+1)

Here we have defined a Macro with name G(y), which is to be replaced by its value, that is (y+1)
during compilation. But, what actually happens when we call G(y),
G(1) //Macro will replace it

the preprocessor will expand it like,


(y) (y+1) (1)

You must be thinking why this happened, this happened because of the spacing in Macro definition.
Hence big functions with several expressions can never be used with macro, so Inline functions
were introduced in C++.

2) Complex Argument Problem


In some cases such Macro expressions work fine for certain arguments but when we use complex
arguments problems start arising.
#define MAX(x,y) x>y?1:0

Now if we use the expression,


if(MAX(a&0x0f,0x0f)) // Complex Argument

Macro will Expand to,


if( a&0x0f > 0x0f ? 1:0)

Here precedence of operators will lead to problem, because precedence of & is lower than that of >,
so the macro evaluation will surprise you. This problem can be solved though using parenthesis, but
still for bigger expressions problem will arise.

3) No way to access Private Members of Class


With Macros, in C++ you can never access private variables, so you will have to make those
members public, which will expose the implementation.
class Y

{
int x;

public :

#define VAL(Y::x) // Its an Error

Inline Functions
Inline functions are actual functions, which are copied everywhere during compilation, like
preprocessor macro, so the overhead of function calling is reduced. All the functions defined inside
class definition are by default inline, but you can also make any non-class function inline by using
keyword inline with them.
For an inline function, declaration and definition must be done together. For example,
inline void fun(int a)

return a++;

Some Important points about Inline Functions

1. We must keep inline functions small, small inline functions have better efficiency.
2. Inline functions do increase efficiency, but we should not make all the functions inline. Because if
we make large functions inline, it may lead to code bloat, and might affect the speed too.
3. Hence, it is adviced to define large functions outside the class definition using scope
resolution ::operator, because if we define such functions inside class definition, then they
become inline automatically.
4. Inline functions are kept in the Symbol Table by the compiler, and all the call for such functions is
taken care at compile time.

Access Functions
We have already studied this in topic Accessing Private Data variables inside class. We use access
functions, which are inline to do so.
class Auto

int i;

public:
int getdata()

return i;

void setdata(int x)

i=x;

};

Here getdata() and setdata() are inline functions, and are made to access the private data members
of the class Auto. getdata(), in this case is called Accessor function and setdata() is
a Mutator function.
There can be overlaoded Accessor and Mutator functions too. We will study overloading functions in
next topic.

Limitations of Inline Functions

1. Large Inline functions cause Cache misses and affect performance negatively.
2. Compilation overhead of copying the function body everywhere in the code on compilation, which
is negligible for small programs, but it makes a difference in large code bases.
3. Also, if we require address of the function in program, compiler cannot perform inlining on such
functions. Because for providing address to a function, compiler will have to allocate storage to it.
But inline functions doesn't get storage, they are kept in Symbol table.

Forward References
All the inline functions are evaluated by the compiler, at the end of class declaration.
class ForwardReference

int i;

public:

int f() {return g()+10;} // call to undeclared function

int g() {return i;}

};

int main()
{

ForwardReference fr;

fr.f();

Friend functions
Friend functions are actually not class member function. Friend functions are made to
give privateaccess to non-class functions. You can declare a global function as friend, or a member
function of other class as friend.
Example :
class WithFriend

int i;

public:

friend void fun(); // Global function as friend

};

void fun()

WithFriend wf;

wf.i=10; // Access to private data member

cout << wf.i;

int main()

fun(); //Can be called directly

Hence, friend functions can access private data members by creating object of the class. Similarly
we can also make function of other class as friend, or we can also make an entire class as friend
class.

class Other

void fun();
};

class WithFriend

private:

int i;

public:

void getdata(); // Member function of class WithFriend

friend void Other::fun(); // making function of class Other as friend here

friend class Other; // making the complete class as friend

};

When we make a class as friend, all its member functions automatically become friend functions.

Arrays of Objects

An array is a one of the data structure in C++, that can store a fixed-size sequential collection of
elements of the same data type.

Define an Array in C++


Syntax:

type arrayName [ arraySize ];

An array type can be any valid C++ data types, and array size must be an integer constant
greater than zero.

Example:

double salary[15000];

Initialize an Array in C++


Arrays can be initialized at declaration time:

int age[5]={22,25,30,32,35};
Initializing each element separately in the loop:

int newArray[5];

int n = 0;

// Initializing elements of array seperately

for(n=0;n<sizeof(newArray)/sizeof(newArray[0]);n++)

newArray[n] = n;

A Pictorial Representation of the Array

Accessing Array Elements in C++


int newArray[10];

int n = 0;

// Initializing elements of array seperately

for(n=0;n<sizeof(newArray)/sizeof(newArray[0]);n++)

newArray[n] = n;

}
int a = newArray[5]; // Assigning 5th element of array value to integer 'a'.

Example:

#include <iostream>

using namespace std;

#include <iomanip>

using std::setw;

int main () {

int newArray[5];

int n = 0, p =0;

// Initializing elements of array seperately

for (n=0; n<sizeof(newArray)/sizeof(newArray[0]); n++) {

newArray[n] = n+50;

// print heading

cout << "Element" << setw(10) << "Value" << endl;

// print element's value in loop

for (p=0; p<sizeof(newArray)/sizeof(newArray[0]); p++) {

cout << setw(5) << p << setw(10) << newArray[p] << endl;

return 0;
}

Program Output:

Element Value

0 50

1 51

2 52

3 53

4 54

S-ar putea să vă placă și