1 of 56

Introduction to Object Oriented Programming

    • Object-oriented programming (OOP) is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs.
    • Programming techniques may include features such as data abstraction, encapsulation, messaging, modularity, polymorphism, and inheritance. Many modern programming languages now support OOP.

2 of 56

Programming paradigm :

A programming paradigm is a fundamental style of computer programming. Paradigms differ in the concepts and abstractions used to represent the elements of a program (such as objects, functions, variables, constraints, etc.) and the steps that compose a computation (assignment, evaluation, continuations, data flows, etc.).

3 of 56

Difference Between C and C++

C:

    • C is a procedural Language
    • No virtual function

C++:

  • C++ is a non procedural Language i e Object Oriented Language

4 of 56

Difference Between C and C++

5 of 56

C++ Program

#include <iostream>using namespace std;��int main() {  cout << "Hello World! \n";  return 0;}

Line 1: #include <iostream> is a header file library that lets us work with input

and output objects, such as cout (used in line 5).

Header files add functionality to C++ programs.

Line 2: using namespace std means that we can use names for objects and

variables from the standard library.

Line 5: The cout object, together with the << operator, is used to output values/print text, \n is used to insert a new line.

6 of 56

C++ Program

#include <iostream>using namespace std;//single line commandint main() {  cout << "Hello World! \n";  return 0;}

/* Multi line command */

7 of 56

C++ Variables

Variables are containers for storing data values.

In C++, there are different types of variables (defined with different keywords), for example:

  • int - stores integers (whole numbers), without decimals, such as 123 or -123
  • double - stores floating point numbers, with decimals, such as 19.99 or -19.99
  • char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
  • string - stores text, such as "Hello World". String values are surrounded by double quotes
  • bool - stores values with two states: true or false

8 of 56

C++ Variables Examples

Example 1:

int myNum = 15;cout << myNum;

Example 2:

int myNum;myNum = 15;cout << myNum;

Example 3:

Declare multiple Variables

int x, y, z;x = y = z = 50;cout << x + y + z;

Example 4: Variables

int m = 60;

Example 5: Constants

const int minutesPerHour = 60;� const float PI = 3.14;

The general rules for naming variables are:

  • Names can contain letters, digits and underscores
  • Names must begin with a letter or an underscore (_)
  • Names are case sensitive (myVar and myvar are different variables)
  • Names cannot contain whitespaces or special characters like !, #, %, etc.
  • Reserved words (like C++ keywords, such as int) cannot be used as names

9 of 56

C++ Data Types

int myNum = 5;               // Integer (whole number)�float myFloatNum = 5.99;     // Floating point number�double myDoubleNum = 9.98;   // Floating point number�char myLetter = 'D';         // Character�bool myBoolean = true;       // Boolean�string myText = "Hello";     // String

10 of 56

C++ Operators�

  • Operators are used to perform operations on variables and values.
  • In the example below, we use the + operator to add together two values:
  • int x = 100 + 50;int sum2 = sum1 + 250;      int sum3 = sum2 + sum2;     

C++ divides the operators into the following groups:

11 of 56

Arithmetic Operators�

12 of 56

Assignment Operators

13 of 56

Comparison Operators

Example:

int x = 5;int y = 3;cout << (x > y); // returns 1 (true) because 5 is greater than 3

14 of 56

Logical Operators

#include <iostream>

using namespace std;

int main() {

int x = 5;

int y = 3;

cout << (x > 3 && x < 10); // returns true (1) because 5 is greater than 3 AND 5 is less than 10

return 0;

}

15 of 56

C++ Strings

  • Strings are used for storing text.
  • A string variable contains a collection of characters surrounded by double quotes:

Example:

string greeting = "Hello"; // Create a string variable

String Concatenation:

The + operator can be used between strings to add them together to

make a new string. This is called concatenation:

string firstName = "John ";string lastName = "Doe";string fullName = firstName + lastName;cout << fullName;

16 of 56

C++ Strings

Append

  • A string in C++ is actually an object, which contain functions that can perform certain operations on strings.
  • For example, you can also concatenate strings with the append() function:

string firstName = "John ";string lastName = "Doe";string fullName = firstName.append(lastName);cout << fullName;

Numbers and Strings

int x = 10;int y = 20;int z = x + y;

Output: 30

string x = "10";string y = "20";string z = x + y;

Output:1020

string x = "10";int y = 20;string z = x + y;

Output: Error Message

17 of 56

�String Length

To get the length of a string, use the length() or size() function:

string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";cout << "The length of the txt string is: " << txt.length();

#include <iostream>

#include <string>

using namespace std;

int main() {

string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

cout << "The length of the txt string is: " << txt.size();

return 0;

}

18 of 56

�Access Strings

You can access the characters in a string by referring to its index number inside square brackets [].

This example prints the first character in myString:

string myString = "Hello";cout << myString[0];// Outputs H

Note: String indexes start with 0: [0] is the first character. [1] is the second character, etc.

string myString = "Hello";cout << myString[1];// Outputs e

Change String Characters:

To change the value of a specific character in a string, refer to the index number, and use single quotes:

string myString = "Hello";myString[0] = 'J';cout << myString;// Outputs Jello instead of Hello

19 of 56

Special Characters

string txt = "We are the so-called \"Vikings\" from the north.";

string txt = "It\'s alright.";

string txt = "The character \\ is called backslash.";

20 of 56

User Input Strings

string firstName;�cout << "Type your first name: ";�cin >> firstName; // get user input from the keyboard�cout << "Your name is: " << firstName;�// Type your first name: John// Your name is: John

  • Omitting Namespace
  • You might see some C++ programs that runs without the standard namespace library.
  • The using namespace std line can be omitted and replaced with the std keyword, followed by the :: operator for string (and cout) objects:

  • #include <iostream>#include <string>��int main() {  std::string greeting = "Hello";  std::cout << greeting;  return 0;}

21 of 56

C++ Math

The max(x,y) function can be used to find the highest value of x and y:

cout << max(510);

And the min(x,y) function can be used to find the lowest value of x and y:

cout << min(510);

Other functions, such as sqrt (square root), round (rounds a number) and log (natural logarithm),

can be found in the <cmath> header file:

// Include the cmath library�#include <cmath>��cout << sqrt(64);cout << round(2.6);cout << log(2);

22 of 56

C++ Conditions and If Statements

C++ has the following conditional statements:

  • Use if to specify a block of code to be executed, if a specified condition is true
  • Use else to specify a block of code to be executed, if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false
  • Use switch to specify many alternative blocks of code to be executed

#include <iostream>

using namespace std;

int main() {

if (20 > 18) {

cout << "20 is greater than 18";

}

return 0;

}

if (condition) {�  // block of code to be executed if the condition is true�} else {  // block of code to be executed if the condition is false}

23 of 56

Cont…

#include <iostream>

using namespace std;

int main() {

int time = 20;

if (time < 18) {

cout << "Good day.";

} else {

cout << "Good evening.";

}

return 0;

}

Use the else if statement to specify a new condition if the first condition is false.

if (condition1) {�  // block of code to be executed if condition1 is true�} else if (condition2) {  // block of code to be executed if the condition1 is false and condition2 is trueelse {  // block of code to be executed if the condition1 is false and condition2 is false}

#include <iostream>

using namespace std;

int main() {

int time = 22;

if (time < 10) { cout << "Good morning.";

} else if (time < 20) { cout << "Good day.";

} else { cout << "Good evening.";

}

return 0;

}

24 of 56

C++ Short Hand If Else

#include <iostream>

#include <string>

using namespace std;

int main() {

int time = 20;

string result = (time < 18) ? "Good day." : "Good evening.";

cout << result;

return 0;

}

Short Hand If...Else (Ternary Operator)

There is also a short-hand if else, which is known as the ternary operator because it consists of three operands. It can be used to replace multiple lines of code with a single line. It is often used to replace simple if else statements:

25 of 56

C++ Switch Statements

switch(expression) {�  case x:�    // code block�    break;  case y:    // code block    break;  default:    // code block}

This is how it works:

  • The switch expression is evaluated once
  • The value of the expression is compared with the values of each case
  • If there is a match, the associated block of code is executed
  • The break and default keywords are optional, and will be described later in this chapter

The example below uses the weekday number to calculate the weekday name:

#include <iostream>

using namespace std;

int main() {

int day = 4;

switch (day) {

case 1: cout << "Monday";

break;

case 2: cout << "Tuesday";

break;

case 3: cout << "Wednesday";

break;

case 4: cout << "Thursday";

break;

case 5: cout << "Friday";

break;

case 6: cout << "Saturday";

break;

case 7: cout << "Sunday";

break;

}

return 0; }

26 of 56

C++ While Loop

The while loop loops through a block of code as long as a specified condition is true:

while (condition) {�  // code block to be executed�}

#include <iostream>

using namespace std;

int main() {

int i = 0;

while (i < 5) {

cout << i << "\n";

i++;

}

return 0;

}

27 of 56

The Do/While Loop

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

do {  // code block to be executed�}while (condition);

#include <iostream>

using namespace std;

int main() {

int i = 0;

do {

cout << i << "\n";

i++;

}

while (i < 5);

return 0;

}

28 of 56

C++ For Loop

for (statement 1; statement 2; statement 3) {�  // code block to be executed�}

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

#include <iostream>

using namespace std;

int main() {

for (int i = 0; i <= 10; i = i + 2) {

cout << i << "\n";

}

return 0;

}

#include <iostream> // nested for loop

using namespace std;

int main() {

// Outer loop

for (int i = 1; i <= 2; ++i) {

cout << "Outer: " << i << "\n"; // Executes 2 times

// Inner loop

for (int j = 1; j <= 3; ++j) {

cout << " Inner: " << j << "\n"; // Executes 6 times (2 * 3)

}

}

return 0;

}

29 of 56

C++ Break and Continue

The break statement can also be used to jump out of a loop.

#include <iostream>

using namespace std;

int main() {

for (int i = 0; i < 10; i++) {

if (i == 4) {

break;

}

cout << i << "\n";

}

return 0;

}

The continue statement breaks one iteration (in the loop), if a specified condition occurs,

and continues with the next iteration in the loop.

#include <iostream>

using namespace std;

int main() {

for (int i = 0; i < 10; i++) {

if (i == 4) {

continue;

}

cout << i << "\n";

}

return 0;

}

30 of 56

C++ Arrays

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

To declare an array, define the variable type, specify the name of the array followed by square brackets and specify the number of elements it should store:

string cars[4];

We have now declared a variable that holds an array of four strings. To insert values to it, we can use an array literal - place the values in a comma-separated list, inside curly braces:

string cars[4] = {"Volvo""BMW""Ford""Mazda"};

int myNum[3] = {102030};

#include <iostream>

#include <string>

using namespace std;

int main() {

string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};

cout << cars[0];

return 0;

}

string cars[4] = {"Volvo""BMW""Ford""Mazda"};cars[0] = "Opel";cout << cars[0];// Now outputs Opel instead of Volvo

31 of 56

Classes:

    • In object-oriented programming, a class is a construct that is used as a blueprint to create instances of the class (class instances, class objects, instance objects or just objects).
    • A class defines constituent members which enable class instances to have state and behavior.
    • Data field members (member variables or instance variables) enable a class object to maintain state. Other kinds of members, especially methods, enable a class object's behavior.
    • Class instances are of the type of the associated class.

32 of 56

Classes:

  • For example, an instance of the class "Fruit" (a "Fruit" object) would be of the type "Fruit". A class usually represents a noun, such as a person, place or (possibly quite abstract) thing.
  • Programming languages that include classes as a programming construct subtly differ in their support for various class-related features. Most support various forms of class inheritance.
  • Many languages also support advanced encapsulation control features, such as access specifiers.

33 of 56

Object:

    • Object is an run time entity.

    • Is an Instance of class

    • Represents a Place ,Person ,anything that have some attributes.

34 of 56

Objects and Instances:

    • There is a very important distinction between an object and an instance of an object. An object is actually a definition, or a template for instances of that object.
    • An instance of an object is an actual thing that can be manipulated. For instance, we could define a Person object, which may include such member data as hair color, eye color, height, weight, etc.
    • An instance of this object could be "Dave" and Dave has values for hair color, eye color, etc. This allows for multiple instances of an object to be created.

35 of 56

C++ Classes/Objects

  • 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 Class:

class MyClass {       // The class�  public:             // Access specifier�    int myNum;        // Attribute (int variable)�    string myString;  // Attribute (string variable)�};

36 of 56

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.
  • To create an object of MyClass, specify the class name, followed by the object name. To access the class attributes (myNum and myString), use the dot syntax (.) on the object:

class MyClass {       // The class�  public:             // Access specifier�    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";  cout << myObj.myNum << "\n";

  cout << myObj.myString;  return 0;

}

37 of 56

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

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 (.):

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

38 of 56

Class Methods

  • 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;}

39 of 56

Class Methods

Parameters: You can also add parameters:

#include <iostream>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;}

40 of 56

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 ():

class MyClass {     // The class�  public:           // Access specifier�    MyClass() {     // Constructor�      cout << "Hello World!";    }};int main() {  MyClass myObj;    // Create an object of MyClass (this will call the constructor)�  return 0;}

Note: The constructor has the same name as the class, it is always public,

and it does not have any return value.

41 of 56

Constructor Parameters�

  • Constructors can also take parameters (just like regular functions), which can be

useful for setting initial values for attributes.

  • The following class have brandmodel and year attributes, and a constructor with

different parameters. Inside the constructor we set the attributes equal to the

constructor parameters (brand=x, etc). When we call the constructor (by creating an

object of the class), we pass parameters to the constructor, which will set the value

of the corresponding attributes to the same:

42 of 56

Constructor Parameters�

class Car {        // The class�  public:          // Access specifier�    string brand, model;  // Attributes�    int year;      // Attribute�    Car(string x, string y, int z) { // Constructor with parameters�      brand = x;      model = y;      year = z;    } };int main() {  // Create Car objects and call the constructor with different values�  Car carObj1("BMW""X5"1999);  Car carObj2("Ford""Mustang"1969);  cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";  cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";  return 0;}

43 of 56

Constructor Parameters�

Just like functions, constructors can also be defined outside the class. First, declare the constructor inside the class, and then define it outside of the class by specifying the name of the class, followed by the scope resolution :: operator, followed by the name of the constructor (which is the same as the class):

class Car {        // The class�  public:          // Access specifier�    string brand, model;  // Attributes�    int year;      // Attribute�    Car(string x, string y, int z); // Constructor declaration�};// Constructor definition outside the class�Car::Car(string x, string y, int z) {  brand = x;  model = y;  year = z;}

44 of 56

Constructor Parameters�

int main() {�// Create Car objects and call the constructor with different values�  Car carObj1("BMW""X5"1999);�  Car carObj2("Ford""Mustang"1969);��  // Print values�  cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";�  cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";�  return 0;�}�

45 of 56

C++ Access Specifiers�

In C++, there are three access specifiers:

  • public - members are accessible from outside the class
  • private - members cannot be accessed (or viewed) from outside the class
  • protected - members cannot be accessed from outside the class, however, they can be accessed in inherited classes. 

class MyClass {  public:    // Public access specifier�    int x;   // Public attribute�  private:   // Private access specifier�    int y;   // Private attribute�};��int main() {  MyClass myObj;  myObj.x = 25;  // Allowed (public)�  myObj.y = 50;  // Not allowed (private)�  return 0;}

46 of 56

Data Encapsulation and Abstraction:

    • Data encapsulation, sometimes referred to as data hiding.

    • Data Encapsulation and Data Abstraction is one of the most striking feature of object oriented programming.

    • The wrapping up of data and code into a single unit is called data encapsulation. The data is not accessible to the outside world only those functions which are wrapped into a class can only access the private data of the class.

Contd…

47 of 56

    • The concept of data encapsulation is supported in C++ through the use of the public, protected and private keywords which are placed in the declaration of the class.

Note :

    • Anything in the class placed after the public keyword is accessible to all the users of the class

    • Elements placed after the protected keyword are accessible only to the methods of the class or classes derived from that class

    • Elements placed after the private keyword are accessible only to the methods of the class.

48 of 56

C++ Encapsulation

The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To achieve this, you must declare class variables/attributes as private (cannot be accessed from outside the class). If you want others to read or modify the value of a private member, you can provide public get and set methods.

Why Encapsulation?

  • It is considered good practice to declare your class attributes as private (as often as you can).
  • Encapsulation ensures better control of your data, because you (or others) can change one part of the code without affecting other parts
  • Increased security of data

49 of 56

C++ Encapsulation

#include <iostream>using namespace std;class Employee {  private:    // Private attribute�    int salary;  public:    // Setter�    void setSalary(int s) {      salary = s;    }    // Getter�    int getSalary() {      return salary;    } };��int main() {  Employee myObj;  myObj.setSalary(50000);  cout << myObj.getSalary();  return 0; }

50 of 56

Inheritance :

    • Inheritance is one of the most striking feature of object oriented programming.

    • Inheritance is the process by which one class can acquire the properties of another class.

    • The new classes, known as subclasses (or derived classes), inherit attributes and behavior of the pre-existing classes, which are referred to as superclasses (or ancestor classes). The inheritance relationships of classes gives rise to a hierarchy

Contd…

51 of 56

    • A superclass, base class, or parent class is a class from which other classes are derived. The classes that are derived from a superclass are known as child classes, derived classes, or subclasses.

    • In object-oriented programming (OOP), inheritance is a way to compartmentalize and reuse code by creating collections of attributes and behaviors called objects which can be based on previously created objects.

52 of 56

C++ Inheritance

In C++, it is possible to inherit attributes and methods from one class to another.

We group the "inheritance concept" into two categories:

  • derived class (child) - the class that inherits from another class
  • base class (parent) - the class being inherited from

To inherit from a class, use the : symbol.

In the example below, the Car class (child) inherits the attributes and methods from the Vehicle class (parent):

53 of 56

C++ Inheritance

// Base class�class Vehicle {  public:    string brand = "Ford";    void honk() {      cout << "Tuut, tuut! \n" ;    }};// Derived class�class Car: public Vehicle {  public:    string model = "Mustang";};

int main() {  Car myCar;  myCar.honk();  cout << myCar.brand + " " + myCar.model;  return 0;}

54 of 56

C++ Multilevel Inheritance

// Base class (parent)�class MyClass {  public:    void myFunction() {      cout << "Some content in parent class." ;    }};// Derived class (child)�class MyChild: public MyClass {};// Derived class (grandchild)�class MyGrandChild: public MyChild {};int main() {  MyGrandChild myObj;  myObj.myFunction();  return 0;}

A class can also be derived from one class, which is already derived from another class.

In the following example, MyGrandChild is derived from class MyChild (which is derived from MyClass).

55 of 56

C++ Multiple Inheritance

// Base class�class MyClass {  public:    void myFunction() {      cout << "Some content in parent class." ;    } };// Another base class�class MyOtherClass {  public:    void myOtherFunction() {      cout << "Some content in another class." ;    } };// Derived class�class MyChildClass: public MyClass, public MyOtherClass {}; int main() {  MyChildClass myObj;  myObj.myFunction();  myObj.myOtherFunction();  return 0;}

A class can also be derived from more than one base class, using a comma-separated list:

56 of 56

C++ Inheritance Access

// Base class�class Employee {�  protected// Protected access specifier�    int salary;};

// Derived class�class Programmer: public Employee {  public:    int bonus;    void setSalary(int s) {      salary = s;    }    int getSalary() {      return salary;    } };int main() {  Programmer myObj;  myObj.setSalary(50000);  myObj.bonus = 15000;  cout << "Salary: " << myObj.getSalary() << "\n";  cout << "Bonus: " << myObj.bonus << "\n";  return 0; }