1 of 32

Object Oriented Programming��With��C++

Book : E Balagurusamy

2 of 32

  • Object Oriented programming (OOP) is a programming paradigm that relies on the concept of classes and objects.
  • It is used to structure a software program into simple, reusable pieces of code blueprints (usually called classes), which are used to create individual instances of objects.
  • There are many object-oriented programming languages including JavaScript, C++, Java, and Python.

3 of 32

Basic terminology

​

  • object

- usually a person, place or thing (a noun)

  • method

- an action performed by an object (a verb)

  • attribute

- description of objects in a class

  • class

- a category of similar objects (such as automobiles)

- does not hold any values of the object’s attributes

​

3

4 of 32

Example for attributes and methods

Attributes:

    • manufacturer’s name
    • model name
    • year made
    • color
    • number of doors
    • size of engine
    • etc.

​

Methods:

    • Define data items (specify manufacturer’s name, model, year, etc.)
    • Change a data item (color, engine, etc.)
    • Display data items
    • Calculate cost
    • etc.

​

4

5 of 32

Why OOP?

  • Save development time (and cost) by reusing code

once an object class is created it can be used in other applications

  • Easier debugging

classes can be tested independently

reused objects have already been tested

​

5

6 of 32

Building blocks of OOP

  • Classes
  • Objects
  • Methods
  • Attributes

7 of 32

Specifying a Class

  • A class is a way to bind the data and its associated functions together.

Class specification has two parts:

  • Class declaration
  • Class function definition

Class declaration describes the type and scope of its members.

Class function definitions describe how the class function are implemented.

The general form of a class declaration is:�class class_name�{�private:�variable declaration;�function declaration;�public:�variable declaration;�function declaration;�};

8 of 32

A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a pair of curly braces, terminated by a semicolon.

  • Functions and variable are called as class member.
  • Private and public are access modifier, known for visibility labels. These keyword are followed by a semicolon.
  • In a class by default all the data and functions member are private.
  • A public data and functions can be accessed from outside the class anywhere within the scope of the class object. 
  • Private data and functions can only be accessed from within the class itself.

�

9 of 32

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.

​

10 of 32

Attributes

​

  • Attributes are the information that is stored. Attributes are defined in the Class template.
  • When objects are instantiated individual objects contain data stored in the Attributes field.

​

​

Methods

  • Methods represent behaviors. Methods perform actions;
  • methods might return information about an object, or update an object’s data. The method’s code is defined in the class definition.

​

​

​

11 of 32

Two Versions of C++

  • A traditional-style C++ program -

11

#include <iostream.h>��int main()�{� /* program code */� return 0;�}

12 of 32

Two Versions of C++ (cont.)

  • A modern-style C++ program that uses the new-style headers and a namespace -

12

#include <iostream>�using namespace std;��int main()�{� /* program code */� return 0;�}

13 of 32

Namespaces

  • A namespace is a declarative region.
  • It localizes the names of identifiers to avoid name collisions.
  • The contents of new-style headers are placed in the std namespace.
  • A newly created class, function or global variable can put in an existing namespace, a new namespace, or it may not be associated with any namespace

​

13

14 of 32

  • std is namespace where ANSI C++ standard class libraries are defined.
  • All program must define it.
  • This will bring all the identifier defined in the std to the current global scope.
  • using and namespace is a keyword.

15 of 32

C++ Program

16 of 32

C++ Program

17 of 32

Design Principles of OOP

Four main design principles of Object-Oriented Programming(OOP):

​

  • Encapsulation
  • Abstraction
  • Polymorphism
  • Inheritance

​

17

18 of 32

Encapsulation

  • Encapsulation means containing all important information inside an object, and only exposing selected information to the outside world.
  • Attributes and behaviors are defined by code inside the class template

Analogy:

  • When you log into your email, compose and send a mail. Again there is a whole lot of background processing involved, verifying the recipient, sending request to the email server, sending your email. Here you are only interested in composing and clicking on the send button. What really happens when you click on the send button, is hidden from you.

​

18

19 of 32

Abstraction

  • Focus only on the important facts about the problem at hand
  • Act of representing essential feature without including background details.
  • Abstraction means that the user interacts with only selected attributes and methods of an object.

Analogy:

  • When you drive a car, you don’t have to know how the gasoline and air are mixed and ignited.
  • Instead you only have to know how to use the controls.
  • Draw map

19

20 of 32

Polymorphism

  • Polymorphism means designing objects to share behaviors.
  • Polymorphism allows the same method to execute different behaviors in two ways: method overriding and method overloading.

​

Method Overriding

Runtime polymorphism uses method overriding. In method overriding, a child class can provide a different implementation than its parent class

Method Overloading

Compile Time polymorphism uses method overloading. Methods or functions may have the same name, but a different number of parameters passed into the method call. Different results may occur depending on the number of parameters passed in.

Analogy:

  • In English, bank can mean side of a river or a place to put money
  • Suppose you write a method addition, when you pass two integer it adds two numbers and if you pass strings then it concatenate two strings

​

​

​

20

21 of 32

Inheritance

  • Inheritance allows classes to inherit features of other classes. Put another way, parent classes extend attributes and behaviors to child classes. Inheritance supports reusability.
  • If basic attributes and behaviors are defined in a parent class, child classes can be created extending the functionality of the parent class, and adding additional attributes and behaviors.
  • Classes with properties in common can be grouped so that their common properties are only defined once.
  • Superclass – inherit its attributes & methods to the subclass(es).
  • Subclass – can inherit all its superclass attributes & methods besides having its own unique attributes & methods.

​

21

22 of 32

Constructors

  • 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 and 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.
  • It is called constructor because it constructs the value of data members of the class.

23 of 32

  • When a class contains a constructor, object created by the class initialized automatically.

Integer c1; not only creates the object c1 but also intializes its data member.

A constructor is declared and defined as follows:

class integer

{

int m,n;

public:

integer();

...............

};

Integer::integer()

{

m=0;n=0;

}

​

24 of 32

How constructors are different from a normal member function?�

  • A constructor is different from normal functions in following ways:
  • Constructor has same name as the class itself
  • Constructors don’t have return type
  • A constructor is automatically called when an object is created.
  • If we do not specify a constructor, C++ compiler generates a default constructor for us (expects no parameters and has an empty body).

​

25 of 32

Types of Constructors

Default Constructors: Default constructor is the constructor which doesn’t take any argument. It has no parameters.

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

}

​

​

Note: Even if we do not define any constructor explicitly, the compiler will automatically

provide a default constructor implicitly. The default value of variables is 0 in case of

automatic initialization.

 

​

26 of 32

#include <iostream>

using namespace std;

 

class Test

{

static int x;

public:

Test() { x++; }

static int getX() {return x;}

};

 

int Test::x = 0;

 

int main()

{

cout << Test::getX() << " ";

Test t[5];

cout << Test::getX();

}

​

What will be the output

27 of 32

Parameterized Constructors

  •  It is possible to pass arguments to constructors. Typically, these arguments help initialize an object when it is created.
  • To create a parameterized constructor, simply add parameters to it the way you do to any other function. When you define the constructor’s body, use the parameters to initialize the object.

A constructor integer() may be modified is declared and defined as follows:

class integer

{

int m,n;

public:

integer(int x, int n);

...............

};

integer::integer(int x, int y)

{

m=x;n=y;

}

When object is intialized, we must pass intials values as arguments to the constructor function.

By calling constructor explicitly: integer int1=integer(0,100);

By calling constructor implicitly: integer int1(0,100);

28 of 32

// CPP program to illustrate

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

}

​

29 of 32

Copy Constructor

  • A copy constructor is a member function which initializes an object using another object of the same class.
  • A copy constructor has the following general function prototype:

ClassName (const ClassName &old_obj);

Following is a simple example of copy constructor.

#include<iostream>

using namespace std;

 

class Point

{

private:

    int x, y;

public:

    Point(int x1, int y1) { x = x1; y = y1; }

 

    // Copy constructor

    Point(const Point &p2) {x = p2.x; y = p2.y; }

 

    int getX()            {  return x; }

    int getY()            {  return y; }

};

 

​

int main()

{

    Point p1(10, 15);

    Point p2 = p1;

 

 // Let us access values assigned by constructors

    cout << "p1.x = " << p1.getX() << ", p1.y = “

<< p1.getY();

    cout << "\np2.x = " << p2.getX() << ", p2.y = “

<< p2.getY();

 

    return 0;

}

​

30 of 32

When is copy constructor called?

In C++, a Copy Constructor may be called in following cases:�1. When an object of the class is returned by value.�2. When an object of the class is passed (to a function) by value as an argument.�3. When an object is constructed based on another object of the same class.�4. When compiler generates a temporary object.

31 of 32

Destructors in C++�

  • What is destructor?�Destructor is a member function which destructs or deletes an object.
  • When is destructor called?�A destructor function is called automatically when the object goes out of scope:�(1) the function ends�(2) the program ends�(3) a block containing local variables ends�(4) a delete operator is called 
  • How destructors are different from a normal member function?�Destructors have same name as the class preceded by a tilde (~)�Destructors don’t take any argument and don’t return anything

​

32 of 32

class String

{

private:

    char *s;

    int size;

public:

    String(char *); // constructor

    ~String();      // destructor

};

  

String::String(char *c)

{

    size = strlen(c);

    s = new char[size+1];

    strcpy(s,c);

}

  

String::~String()

{

    delete []s;

}

​

Can there be more than one destructor in a class?�No, there can only one destructor in a class with classname

preceded by ~, no parameters and no return type.