OOPS NOTES OF C++ FOR EXAM

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

CREATING OBJECT OF A CLASS

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 . OPERATOIR USED TO ACCESS OBJECT


myObj.myNum = 15;
myObj.myString = "Some text";

// Print attribute values


cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
}

// THE EXAMPLE OF SIMPLE CONSTRUCTOR

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;
}
Constructor with parameters

class Car { // The class


public: // Access specifier
string brand; // Attribute
string model; // Attribute
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);

// Print values
cout << carObj1.brand << " " << carObj1.model << " " <<
carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " <<
carObj2.year << "\n";
return 0;
}
Constructor definition outside the class

class Car { // The class


public: // Access specifier
string brand; // Attribute
string model; // Attribute
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;
}

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

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. You will learn more
about Inheritance later.
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.

 In normal terms Encapsulation is defined as wrapping up of data and


information under a single unit. In Object Oriented Programming,
Encapsulation is defined as binding together the data and the functions
that manipulates them.

 Example >>

>> Consider a real life example of encapsulation, in a company there are


different sections like the accounts section, finance section, sales section
etc. The finance section handles all the financial transactions and keep
records of all the data related to finance. Similarly the sales section
handles all the sales related activities and keep records of all the sales.
Now there may arise a situation when for some reason an official from
finance section needs all the data about sales in a particular month. In
this case, he is not allowed to directly access the data of sales section.
He will first have to contact some other officer in the sales section and
then request him to give the particular data. This is what encapsulation is.
Here the data of sales section and the employees that can manipulate
them are wrapped under a single name “sales section”.
// c++ program to explain

// Encapsulation

#include<iostream>

using namespace std;

class Encapsulation{

private:

// data hidden from outside world

int x;

public:

// function to set value of // variable x

void set(int a)

x =a; }

// function to return value of variable x

int get()

{ return x; }

};

int main()

Encapsulation obj;

obj.set(5);

cout<<obj.get();

return 0;

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

#include <iostream>
class Sum {
private: int a,b,c;
public:
void add(){
cout<<"Enter any two numbers: ";
cin>>a>>b;
c=a+b;
cout<<"Sum: "<<c; }
};
int main(){
sum s;
s.add();
return 0 ; }
Inheritance in C++
>> The capability of a class to derive properties and characteristics from another class is
called Inheritance. Inheritance is one of the most important features of Object-Oriented
Programming.

 Sub Class: The class that inherits properties from another class is called Subclass or
Derived Class.
 Super Class: The class whose properties are inherited by a subclass is called Base
Class or Superclass.

Why and when to use inheritance?


Consider a group of vehicles. You need to create classes for Bus, Car, and Truck. The
methods fuelAmount(), capacity(), applyBrakes() will be the same for all three classes. If
we create these classes avoiding inheritance then we have to write all of these functions
in each of the three classes as shown below figure:

To avoid this type of situation, inheritance is used. If we create a class Vehicle


and write these three functions in it and inherit the rest of the classes from the
vehicle class, then we can simply avoid the duplication of data and increase re-
usability. Look at the below diagram in which the three classes are inherited
from vehicle class:
// C++ program to demonstrate implementation of Inheritance

#include <bits/stdc++.h>

using namespace std;

// Base class

class Parent {

public:

int id_p; };

// Sub class inheriting from Base Class(Parent)

class Child : public Parent {

public:

int id_c; };

// main function

int main() {

Child obj1;

// An object of class child has all data members

// and member functions of class parent

obj1.id_c = 7;

obj1.id_p = 91;

cout << "Child id is: " << obj1.id_c << '\n';

cout << "Parent id is: " << obj1.id_p << '\n';

return 0; }
#include <iostream>

#include <string>

using namespace std;

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

}
1. Single Inheritance: In single inheritance, a class is allowed to inherit
from only one class. i.e. one subclass is inherited by one base class only.

2. Single inheritance is defined as the inheritance in which a derived class is


inherited from the only one base class. Where 'A' is the base class, and 'B' is
the derived class.

3. class subclass_name : access_mode base_class


{
// body of subclass
};

// C++ program to explain Single inheritance

#include<iostream>

using namespace std;

// base class

class Vehicle {

public:

Vehicle(){
cout << "This is a Vehicle\n";

};

// sub class derived from a single base classes

class Car : public Vehicle {

};

// main function

int main(){

// Creating object of sub class will

// invoke the constructor of base classes

Car obj;

return 0;}

Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class


can inherit from more than one class. i.e one subclass is inherited from more
than one base class.

A class can also be derived from more than one base class, using a comma-
separated list
#include <iostream>

using namespace std;

// Base class

class MyClass {

public:

void myFunction() {

cout << "Some content in parent class.\n" ;

}};

// Another base class

class MyOtherClass {

public:

void myOtherFunction() {

cout << "Some content in another class.\n" ;

}};

// Derived class

class MyChildClass: public MyClass, public MyOtherClass {

};

int main() {

MyChildClass myObj;

myObj.myFunction();

myObj.myOtherFunction();

RETURN 0; }
// C++ program to explain multiple inheritance

#include <iostream>

using namespace std;

// first base class

class Vehicle {

public:

\\THIS IS A CONSTRUCTOR Vehicle() { cout << "This is a Vehicle\n"; } };

// second base class

class FourWheeler {

public:

FourWheeler(){

cout << "This is a 4 wheeler Vehicle\n";

};

// sub class derived from two base classes

class Car : public Vehicle, public FourWheeler {

};

// main function

int main(){

// Creating object of sub class will invoke the constructor of base classes.

Car obj;

return 0;}
Multilevel Inheritance: In this type of inheritance, a derived class is created
from another derived class.

multilevel inheritance, a class has more than one parent class. For example, if we
take animals as a base class then mammals are the derived class which has features of
animals and then humans are the also derived class that is derived from sub-class
mammals which inherit all the features of mammals.

Modes of Inheritance: There are 3 modes of inheritance.


1. Public Mode: If we derive a subclass from a public base class. Then the
public member of the base class will become public in the derived class and
protected members of the base class will become protected in the derived
class.
2. Protected Mode: If we derive a subclass from a Protected base class. Then
both public members and protected members of the base class will become
protected in the derived class.
3. Private Mode: If we derive a subclass from a Private base class. Then both
public members and protected members of the base class will become
Private in the derived class.

// C++ program to implement Multilevel Inheritance


#include <iostream>

using namespace std;

// base class

class Vehicle {

public:

Vehicle() { cout << "This is a Vehicle\n"; } };

// first sub_class derived from class vehicle

class fourWheeler : public Vehicle {

public:

fourWheeler(){

cout << "Objects with 4 wheels are vehicles\n";

} };

// sub class derived from the derived base class fourWheeler

class Car : public fourWheeler {

public:

Car() { cout << "Car has 4 Wheels\n"; }

};

int main(){

// Creating object of sub class will invoke the constructor of base classes.

Car obj;

return 0;}
Hierarchical Inheritance: In this type of inheritance, more than one
subclass is inherited from a single base class. i.e. more than one derived
class is created from a single base class

// C++ program to implement Hierarchical Inheritance

#include <iostream>

using namespace std;

// base class

class Vehicle {

public:

Vehicle() { cout << "This is a Vehicle\n"; }

};

// first sub class

class Car : public Vehicle {

};

// second sub class

class Bus : public Vehicle {

};

int main(){

// Creating object of sub class will invoke the constructor of base class.

Car obj1;

Bus obj2;

return 0;

}
POLYMORFISM

The word polymorphism means having many forms.A real-life example of


polymorphism, a person at the same time can have different
characteristics. Like a man at the same time is a father, a husband, an
employee. So the same person posses different behavior in different
situations. This is called polymorphism.

Compile time polymorphism: This type of polymorphism is achieved by


function overloading or operator overloading.

 Function Overloading: When there are multiple functions with same name
but different parameters then these functions are said to be overloaded.
Functions can be overloaded by change in number of
arguments or/and change in type of arguments.
// C++ program for function overloading

#include <bits/stdc++.h>

using namespace std;

class Geeks

public:

// function with 1 int parameter

void func(int x)

cout << "value of x is " << x << endl;

// function with same name but 1 double parameter

void func(double x)

cout << "value of x is " << x << endl;

// function with same name and 2 int parameters

void func(int x, int y)

{
cout << "value of x and y is " << x << ", " << y << endl;

};

int main() {

Geeks obj1;

// Which function is called will depend on the parameters passed

// The first 'func' is called

obj1.func(7);

// The second 'func' is called

obj1.func(9.132);

// The third 'func' is called

obj1.func(85,64);

return 0;

Operator Overloading: C++ also provide option to overload operators. For


example, we can make the operator (‘+’) for string class to concatenate two
strings. We know that this is the addition operator whose task is to add two
operands. So a single operator ‘+’ when placed between integer operands ,
adds them and when placed between string operands, concatenates them.
List of operators that cannot be overloaded
1) Scope Resolution Operator (::)
2) Ternary or Conditional Operator (?:)
3) Member Access or Dot operator (.)
4) Pointer-to-member Operator (.*)
5) Object size Operator (sizeof)
6) Object type Operator(typeid)
7) static_cast (casting operator)
8) const_cast (casting operator)
9) reinterpret_cast (casting operator)
10) dynamic_cast (casting operator)

// CPP program to illustrate Operator Overloading

#include<iostream>

using namespace std;

class Complex {

private:

int real, imag;

public:

Complex(int r = 0, int i =0) {real = r; imag = i;}

// This is automatically called when '+' is used with

// between two Complex objects

Complex operator + (Complex const &obj) {

Complex res;

res.real = real + obj.real;

res.imag = imag + obj.imag;

return res;

void print() { cout << real << " + i" << imag << endl; }

};
int main(){

Complex c1(10, 5), c2(2, 4);

Complex c3 = c1 + c2; // An example call to "operator+"

c3.print(); }

Runtime polymorphism: This type of polymorphism is achieved by Function Overriding.

 Function overriding on the other hand occurs when a derived class has a definition for one
of the member functions of the base class. That base function is said to be overridden

Function overriding is a feature that allows us to have a same function in child class
which is already present in the parent class. A child class inherits the data members and
member functions of parent class, but when you want to override a functionality in the
child class then you can use function overriding.

To override a function you must have the same signature in child class. By signature I
mean the data type and sequence of parameters. Here we don’t have any parameter in
the parent function so we didn’t use any parameter in the child function.

#include <iostream>
using namespace std;
class BaseClass {
public:
void disp(){
cout<<"Function of Parent Class";
}
};
class DerivedClass: public BaseClass{
public:
void disp() {
cout<<"Function of Child Class";
}
};
int main() {
DerivedClass obj = DerivedClass();
obj.disp();
return 0;
}

// C++ program for function overriding

#include <bits/stdc++.h>

using namespace std;

class base{
public:

virtual void print ()

{ cout<< "print base class" <<endl; }

void show ()

{ cout<< "show base class" <<endl; }

};

class derived:public base

public:

void print () //print () is already virtual function in derived class, we


could also declared as virtual void print () explicitly

{ cout<< "print derived class" <<endl; }

void show ()

{ cout<< "show derived class" <<endl; }

};

//main function

int main() {

base *bptr;

derived d;

bptr = &d;

//virtual function, binded at runtime (Runtime polymorphism)

bptr->print();
// Non-virtual function, binded at compile time

bptr->show();

return 0 ;

Data abstraction
is one of the most essential and important feature of object oriented programming in C++. Abstraction
means displaying only essential information and hiding the details. Data abstraction refers to providing
only essential information about the data to the outside world, hiding the background details or
implementation.
Consider a real life example of a man driving a car. The man only knows that pressing the accelerators
will increase the speed of car or applying brakes will stop the car but he does not know about how on
pressing accelerator the speed is actually increasing, he does not know about the inner mechanism of
the car or the implementation of accelerator, brakes etc in the car. This is what abstraction is.

Abstraction using Classes: We can implement Abstraction in C++ using classes. Class helps us to
group data members and member functions using available access specifiers. A Class can decide
which data member will be visible to outside world and which is not.
Abstraction in Header files: One more type of abstraction in C++ can be header files. For
example, consider the pow() method present in math.h header file. Whenever we need to calculate
power of a number, we simply call the function pow() present in the math.h header file and pass the
numbers as arguments without knowing the underlying algorithm according to which the function is
actually calculating power of numbers.
Abstraction using access specifiers

Access specifiers are the main pillar of implementing abstraction in C++. We can use access specifiers
to enforce restrictions on class members. For example:
 Members declared as public in a class, can be accessed from anywhere in the program.
 Members declared as private in a class, can be accessed only from within the class. They are not
allowed to be accessed from any part of code outside the class.

Advantages of Data Abstraction:

 Helps the user to avoid writing the low level code


 Avoids code duplication and increases reusability.
 Can change internal implementation of class independently without affecting the user.
 Helps to increase security of an application or program as only important details are
provided to the user

#include <iostream>

using namespace std;

class implementAbstraction{
private:

int a, b;

public:

// method to set values of private members

void set(int x, int y){

a = x;

b = y; }

void display(){

cout<<"a = " <<a << endl;

cout<<"b = " << b << endl;

} };

int main(){

implementAbstraction obj;

obj.set(10, 20);

obj.display();

return 0;

What is constructor?
Constructor is a member function of class, whose name is same as the class.
A constructor is a special type of member function of a class which initializes objects of a class. In C++, Constructor is
automatically called when object(instance of class) is created.
Constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is
known as constructors.
Constructor does not have a return value, hence they do not have a return type.
Prototype of Constructors:-
<class-name> (list-of-parameters);
Constructors can be defined inside or outside the class declaration: -
1. Syntax for defining the constructor within the class:
<class-name> (list-of-parameters)
{
// constructor definition
}
2. Syntax for defining the constructor outside the class:
<class-name>: :<class-name> (list-of-parameters)
{
// constructor definition
}

// defining the constructor within the class

#include <iostream>

using namespace std;

class student {

int rno;

char name[10];

double fee;

public:

student(){

cout<<"Enter the RollNo:";

cin>>rno;

cout<<"Enter the Name:";

cin>>name;

cout<<"Enter the Fee:";

cin>>fee;

void display(){
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;

};

int main()

student s; // constructor gets called automatically when

// we create the object of the class

s.display();

return 0;

// defining the constructor outside the class

#include<iostream>

using namespace std;

class student

int rno;

char name[50];

double fee;

public:
student();

void display();

};

student::student()

cout<<"Enter the RollNo:";

cin>>rno;

cout<<"Enter the Name:";

cin>>name;

cout<<"Enter the Fee:";

cin>>fee;

void student::display()

cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;

int main()

{
student s;

s.display();

return 0;

What is a destructor?
Destructor is an instance member function which is invoked automatically whenever an object is going to be destroyed. Meaning ,
a destructor is the last function that is going to be called before an object is destroyed.
The thing is to be noted here, if the object is created by using new or the constructor uses new to allocate memory which res ides
in the heap memory or the free store, the destructor should use delete to free the memory.
Syntax:
~constructor-name();
Properties of Destructor:
 Destructor function is automatically invoked when the objects are destroyed.
 It cannot be declared static or const.
 The destructor does not have arguments.
 It has no return type not even void.
 An object of a class with a Destructor cannot become a member of the union.
 A destructor should be declared in the public section of the class.
 The programmer cannot access the address of destructor.
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 are destructors 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
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.
When do we need to write a user-defined destructor?

If we do not write our own destructor in class, compiler creates a default destructor for us. The default destructor works fi ne
unless we have dynamically allocated memory or pointer in class. When a class contains a pointer to memory allocated in class,
we should write a destructor to release memory before the class instance is destroyed. This must be done to avoid memory leak .
Can a destructor be virtual?

Yes, In fact, it is always a good idea to make destructors virtual in base class when we have a virtual function.

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

DISTRUCTOR ANOTHER EXAMPLE

#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; }
RANDOM NOTES

Generics in C++
Generics is the idea to allow type (Integer, String, … etc and user-defined types) to be a parameter to methods, classes and interfaces. For
example, classes like an array, map, etc, which can be used using generics very efficiently. We can use them for any type.
The method of Generic Programming is implemented to increase the efficiency of the code. Generic Programming enables the programmer to
write a general algorithm which will work with all data types. It eliminates the need to create different algorithms if the data type is an integer,
string or a character.
The advantages of Generic Programming are
1. Code Reusability
2. Avoid Function Overloading
3. Once written it can be used for multiple times and cases.
Generics can be implemented in C++ using Templates. Template is a simple and yet very powerful tool in C++. The simple idea is to pass data
type as a parameter so that we don’t need to write the same code for different data types. For example, a software company may need sort() for
different data types. Rather than writing and maintaining the multiple codes, we can write one sort() and pass data type as a parameter.

#include <iostream>

using namespace std;

// One function works for all data types. This would work even for user defined types
if operator '>' is overloaded

template <typename T>

T myMax(T x, T y){

return (x > y) ? x : y;

int main(){

// Call myMax for int

cout << myMax<int>(3, 7) << endl;

// call myMax for double

cout << myMax<double>(3.0, 7.0) << endl;

// call myMax for char

cout << myMax<char>('g', 'e') << endl;

RETURN 0 ;}
Class: A class in C++ is the building block that leads to Object-Oriented
programming. It is a user-defined data type, which holds its own data members
and member functions, which can be accessed and used by creating an instance of
that class. A C++ class is like a blueprint for an object.
For Example: Consider the Class of Cars. There may be many cars with different
names and brand but all of them will share some common properties like all of
them will have 4 wheels, Speed Limit, Mileage range etc. So here, Car is the class
and wheels, speed limits, mileage are their properties.

A Class is a user defined data-type which has data members and member
functions.
Data members are the data variables and member functions are the functions used
to manipulate these variables and together these data members and member
functions defines the properties and behavior of the objects in a Class.
In the above example of class Car, the data member will be speed limit, mileage
etc and member functions can be apply brakes, increase speed etc.

An Object is an instance of a Class. When a class is defined, no


memory is allocated but when it is instantiated (i.e. an object is
created) memory is allocated.

Defining Class and Declaring Objects

A class is defined in C++ using keyword class followed by the name of class. The
body of class is defined inside the curly brackets and terminated by a semicolon at
the end.

// Example:

// Friend class emplimentetin

#include<iostream>
using namespace std;

class A{

int x;

public:

A()

x=10;

friend class B; //friend class

};

class B{

public:

void display(A &t)

cout<<endl<<"The value of x="<<t.x;

};

main()
{

A _a;

B _b;

_b.display(_a);

return 0;

You might also like