Introduction to Object Oriented Programming
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.).
Difference Between C and C++
C:
C++:
Difference Between C and C++
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.
C++ Program
#include <iostream>�using namespace std;�//single line command�int main() {� cout << "Hello World! \n";� return 0;�}
/* Multi line command */
C++ Variables
Variables are containers for storing data values.
In C++, there are different types of variables (defined with different keywords), for example:
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:
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
C++ Operators�
C++ divides the operators into the following groups:
Arithmetic Operators�
Assignment Operators
Comparison Operators
Example:
int x = 5;�int y = 3;�cout << (x > y); // returns 1 (true) because 5 is greater than 3
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;
}
C++ Strings
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;
C++ Strings
Append
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
�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;
}
�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
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.";
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
C++ Math
The max(x,y) function can be used to find the highest value of x and y:
cout << max(5, 10);
And the min(x,y) function can be used to find the lowest value of x and y:
cout << min(5, 10);
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);
C++ Conditions and If Statements
C++ has the following conditional statements:
#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�}
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 true�} else {� // 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;
}
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:
C++ Switch Statements
switch(expression) {� case x:� // code block� break;� case y:� // code block� break;� default:� // code block�}
This is how it works:
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; }
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;
}
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;
}
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;
}
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;
}
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] = {10, 20, 30};
#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
Classes:�
Classes:�
Object:�
Objects and Instances:�
C++ Classes/Objects�
Create Class:
class MyClass { // The class� public: // Access specifier� int myNum; // Attribute (int variable)� string myString; // Attribute (string variable)�};
Create an 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;
}
Class Methods�
Methods are functions that belongs to the class.
There are two ways to define functions that belongs to a class:
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;�}
Class Methods�
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;�}
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;�}
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.
Constructor Parameters�
useful for setting initial values for attributes.
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:
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;�}
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;�}
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;�}��
C++ Access Specifiers�
In C++, there are three access specifiers:
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;�}
Data Encapsulation and Abstraction:�
Contd…
�
Note :
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?
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; }
Inheritance :�
Contd…
�
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:
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):
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;�}
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).
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:
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; }