c plus plus Notes

Oops in C++

The main aim of OOP is to bind together the data and the function that operate on them so that no other part of the code can access this data except this function.

Class:     is a user defined data types, which holds its own data member and member functions, which can be accessed and used by creating an instance of that class

Objects:    when a class is defined no memory is allocated but when it is instantiated (i.e, object is created) memory is allocated.

Encapuslation: In OOP, Encapuslation is defined as binding together the data nd the function that manipulates.

Abstraction: Abstraction means displaying only essential information and hiding the details.

Abstraction using classes

Abstraction using Header files (math.h->Pow())

Polymorphism: In a simple words, we can define polymorphism as the ability of message to display more than one form.

  • Operator overloading
  • Function overloading

Inheritance: the capability of class to derive properties and characteristic from another class is called inheritance.

  • Super class
  • Sub class
  • Reusability
  • Dynamic Binding:

In dynamic binding, the code to be executed in response to function call is decided at the run time

Constructor : A constructor is  member function on a class which initialize objects of a class, In C++ constructor is automatically called when an object is created

It has the same name as the class name

Constructor don’t have a return type

  • Default constructor (no Parameter)
  • Parameterized Constructor
  • Copy constructor

Destructor n C++: derived class destructor will be invoked first, then the base class destructor will be invoked.

Access Modifier:

Public : it can be accessed by any class

Private: it cab be accessed only by function in a class (inaccessible outside the class)

Protected: it is also inaccessible outside the class but can be accessed by subclass of that class

Note: if we do not specify any access modifier inside the class then by default the access modifier for the member will be private .

Friend Class: A friend class can access private and protected members of other class in which it is declared as friend.

Ex : Friend Class B;

 

 

Polymorphism:

Compile Time Polymorphism:

  • Operator Overloading
  • Function Overloading

Run Time Polyomorphism

Function Overriding: occurs when a derived class has a definiation of one or more members of base class.

Advantages of Data Abstracion :

  • Avoid Code Duplication and inc reusability.
  • Can change internal implementation of class independently

Structure Vs Class : most important diffrenece is security

A structure s not secure nd cannot hide its member function  and variable while class is secure and can hide its programming and designing details

Local Classes in C++: A class declared inside a function becomes local to tthat function and is called local class

All the methods of local class must be defined inside the class only

Virtual Function and Run Time Polymorphism

A virtual function is member function which is declare within a base class an redefined (override) by derived class.

Function are declared with virtual keywords in base class.

Exception Handling in C++:

  • Try : represent a block of code that can throw an exception
  • Catch : represent a block of ode that get executed when error is thrown
  • Throw: used to throw an exception, there is special catch block

There is a special catch blockà catch(…), it catches all type of error.

Inline Function:  Inline is a request not command it is a function that is expanded inline when it called, when the inline function is called , whole code get insetead or substituted at the point of point function call.

Inline return-type fun()

{



}

Function Overloading :  is a feature in C++ where two or more functions can have same name but different parameters.

Void print (int i)

{

Cout<<” Here is int “<< i<<endl;

}

Void print (float i)

{

Cout<<” Here is float “<< i<<endl;

}

Int main

{

Print(10);

Print(10.12);

}

 

Differences between C and C++

C C++
C  supports procedure programming C++ is known as hybrid language, because it support both procedural and object oriented programming
C does not support the oops concept so it has no support for polymorphism, encapsulation and  inheritance. C++ has support for polymorphism, encapsulation and inheritance as it is an oops language
C is a subset of C++ C++ is superset of C
C contains 32 keywords C++ contain 52 keywords (private, public, protected, try, catch, throw,…)
C is function driven language C++ is an object driven language
Function and operator overloading is not support in C C++ support function support operator overloading
C does not support exception Handling C++ supports exception handling using try and catch

 

Structure : is a collection of dissimilar elements

Static members in C++

Static variable in a function : when a variable is declared as static , space for it gets allocated for the lifetime of the program(default initialized to 0) Even if the function is called multiple time, the space for it is allocated once.

  • Static variable in a class:
  • Declared inside the class body
  • Also known as class member variable
  • They must be defined outside the class
  • Static variable doesn’t belong to any object, but the whole class.
  • There will be only one copy of static member variable for the whole class

Example :    class Account

{

private: int balance;

static float roi;

Public: void setBalanec(int b)

{

balance = b;

}

}

// initialised outside class

float Account :: roi = 3.5f;

void main

{

Account a1;

}

Object can also be declared as a static

Static Account a1;

Static Function in a class: static member function are allowed to access only the static data member or other static member function.

Constructor :

Constructor is a special member function of the class. It is automatically invoke when an object is created.

The syntax of defining constructor with its prototype within a class body and actual definition outside is as shown below

class classname

{



public:



classname();

};

classname :: classname()

{



}

Character sties  of a constructor:

  • It has no return type
  • Constructor has same name as type of class name
  • If we do not specify , then C++ complier generate a default constructor for us.
  • A constructor is invoked automatically as soon as the class object is created.
  • A constructor does not return any value, so return type is not associated with its definition (even void is not used).
  • Constructor are not inherited
  • A constructor cannot be declared as virtual
  • Constructor can be overloaded

Similar to other members, the constructor can be defined either within or outside the body of a class. It can access only data member like member function

Complier generates two constructor by itself:

Default Constructor

Copy Constructor

But if any of the constructor is created by user, then default constructor will not be created by complier.

 

Default Constructor: it does not accept any argument values here, so we use void there, the constructor that does not accept any argument values is called “Default Constructor”

Default : Class_name()

 

update()

{

a=10;

b=20;

}

Example :

#include<iostream.h>

Class Test

{

Public : Test();

};

Test :: Test()

{

cout <<” Constructor of class test called”<<endl;

}

Test y;

void fun()

{

Test C;

cout<<” Here function fun()”<<endl;

}

void main()

{

Test x;

cout<<” Main Function”<endl;

fun();

}

Parameterized Constructor :

Constructor with argument are called “parameterised Constructor”.

Example:

Class_name(Parameters)

update (int x, int y)

{

a=x;

b=y;

}

When a Constructor has been parameterized the object declaration statement such as integer  int may not work.

We must pass the initial value as the argument to the constructor function, when an object is derived. This can be done in 2 ways.

  1. By calling the constructor explicitly
  2. By calling the constructor implicitly

The following declaration illustrate the first methods

Integer int = integer (10, 20);

This statement creates an  integer object int and passes the value ( 10 and 20) to it.

The second is implemented as follows

Integer int (20,40);

Example : Write a C++ Program that demonstrates to create an object and initialize the data members by using parameterized constructor.

 

#include<iostream.h>

#include<conio.h>

class employee

{

int empno;

char empname;

float salary;

public: employee (int eno, char ename[], float es)

{

empno =eno;

strcopy(empname, ename);

salary=es;

}

void display()

{

cout <<“Empname : =”<< empname<<endl;

cout <<“Empno : =”<< empno<<endl;

cout <<“Salary : =”<< salary<<endl;

}

};

void main()

{

employee emp(10, ‘xyz’, 100.00);

emp.display();

}

 

 

Copy Constructor: Class_name (const Class_name and Object)

update(const update & p2)

{

a = p2.a;

b = p2.a;

}

Constructor Overloading

Constructor overloading can be done just like function overloading.

interesting feature of the constructor is that a class can have multiple constructor this is called constructor overloading. All the constructor have the same name as corresponding class and the are either in terms of number of arguments or datatype of their arguments or both

Example : Program to create an object of class type point and initializes its members using overloaded constructor.

#include<iostream.h>

#include<conio.h>

Class point

{

private : int ;

int y;

public : point(vod)

{

x = 0;

y = 0;

}

point( int xpas, int ypas)

{

x = xpas;

y = ypas;

}

void display(void)

{

cout<<  ” x = ” << x << ” \ t ” ;

cout<< ” y = ” << y << endl;

}

};

 

void main()

{

point p1, p2(10, 20);

cout<<“point p1 is “<<endl;

p1.display();

cout<,”oint p2 is “<<endl;

p2.display();

}

Default (Complier’s)  copy Constructor can done only shallow copy

Deep Copy is possible only with use defined constructor in user defined copy constructor, we make sure that pointers at copied object points to new memory location.

Can we make copy constructor private/? Yes

Why argument to copy constructor must be passed as a reference.

Because if we pass value, then it would made to call copy constructor which becomes non-terminate

Destructor

  • Destructor is a member function which destructs or deletes an object
  • Destructor don’t take any argument and don’t have any return type.
  • Only one destructor is possible
  • Destructor cannot be static
  • Actually destructor doesn’t destroy object, it is the last function that invoked before object destroy.

 

Destructor is used, so that before deletion of object we can free space allocated for this resource, between if object gets deleted then space allocated for object will be free but resource doesn’t.

Destructor function inside the class is as fallows

class classname

{

private:


public:


~ classname() // definition of destructor

{



}

};

Example : C++ program to illustrate the numbers of objects created and destroyed.

#include<iostream.h>

#include<conio.h>

class Sample

{

public:

sample()

{

Count = count + 1;

cout<<” The number of objects created…..”<<count<<endl;

}

~sample()

{

cout<<” The number of objects destroyed…..”<<count<<endl;

count = count  – 1;

}

};

void main()

{

cout<<” this is how object is created and destroyed….”<<“\n”;

Sample s1, s2,s3;

}

Operator Overloading

Each  c++ operator has a predefined meaning . most of them are given additional meaning through the concept called “operator overloading”

The main idea behind operator overloading is to use c++ operator with the class objects. As we C++ operator to the built in data types, so we can now apply those operators to the class objects.

Example := + Addition operator) ma be used to add two ints, floats or doubles now, the same can be used add two classes objects, there by + gets overloaded. When a + operator is use with two integer ha different meaning as compared when it is applied to object manipulation.

Operator overloading is carried out with the help of a special kind of function. This function is just like any other C++’s function definition except that the name of the function consist of the keywords operator followed by the one of the C++’s built in operator. Its general form is as fallows

Return_type class _name::operator opr(argument_list)

{

//function body

}

While,

  • Return_type :-> it is data type of return values
  • Class_name-> nam e of the class
  • :: scope resolution operator
  • Operator-> is a keyword
  • Opr-> is C++ built_in operator it may be an unary or binary operator
  • Argument _list-> is a list of argument to be passé
  • Operator opr -> is the function name

class Complex

{

complex operator + (complex &c1)

{

complex  res;

res. a =c1.a;

res .b= c2.b;

}

}

int main{

c = c1 + c2;

}

As ‘_’ can’t add complex no’s directly so we can define a function with name + but we need write operator keyword before it so, we can use all operator this

Friend Class 

A friend class can access the private and protected members of other class in which it is declare as friend.

There can be friend class and friend function.

Class Box

{

Private : Double width;

Public: Friend void printWidth (Box box);

void SetWidth (double Wid);

}

void Box:: SetWidth(Boxdouble Wid)

{

Width = Wid;

}

Void printWidth(Box box)

{

Cout<<box.Width;

}

int main()

{

Box box;

box .SetWidth(14);

printWidth(box);

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Inheritance :

Inheritance it is the process of inheriting properties and behavior of existing class into a new class.

Reusability is the another important feature of OOPs. It is always nice if er could lies something that always exists rather then trying to create some, all over again it would trying only save time and money but also the effort of developing and testing the some over again, it can be implemented n C++ by inheritance,

Inheritance is the most power full feature of Oops . the mechanism of deriving a new class from an old one is called inheritance . the old class is refered to as the “base class” and the new one is called “derived class or subclass”

Based on this relationship inheritance can be classified into 5 forms

Class Subclass : accessmode baseclass

{



}

  • Single Inheritance
  • Mutiple Inhetience
  • Hierarchical Inheritance
  • Multi level Inheritnace
  • Hybried Inheritance

 

Class Base_class

{

};

Class der_class:Base_class

{

};

Example:

Class car

{

};

Class Sports_car: Public Car

{

};

Types of Inheritance

  1. Single Inheritance

A derived class with only one base class is called “Single Inheritance”

Or it is the mechanism in which we inherit the base class feature to a derived class, it is like the parent-child relationship, this single inheritance possesses one-to-one relation.

 

Class A

{


 

 

};

Class B: Public A

{


};

Example: Program to illustrate single Inheritance in public mode.

include<iostream.h>

#include <Conio.h>

class father

{

Private : char name[20];

int age;

Public : Char color[15];

char gender;

int IQ;

void getdata();

void display();

};

class son: public father

{

private : char qualification;

float salary;

public : void read90;

void print();

};

void father :: getdata()

{

Cout<<” Enter the name :”;

Cin>>name;

 

Cout<<” Enter the age :”;

Cin>>age;

 

Cout<<” Enter the color :”;

Cin>>color;

 

Cout<<” Enter the sex :”;

Cin>>sex;

 

Cout<<” Enter the IQ :”;

Cin>>IQ;

}

void father :: display()

{

cout <<“Name =”<<name<<endl;

cout <<“Age =”<<age<<endl;

cout <<“Color =”<<color<<endl;

cout <<“Gender =”<<Gender<<endl;

cout <<“IQ =”<<IQ<<endl;

}

void son :: read()

{

father:: getdata();

cout<<” Enter the qualification:”;

cin>>qualification;

cout<<” Enter the Salary:”;

cin>>salary;

}

void son :: print(void)

{

father :: display();

cout<<” qualification =”<<qualification<<endl;

cout<<” salary = “<<salary<<endl;

}

void main()

{

son s1;

cout<<” Enter the son information…”<<endl;

s1.read();

cout<<“Son’s information is as fallows..”<<endl;

s1.print();

}

  1. Multilevel Inheritance

The mechanism of deriving a class from another derived is known as “Multilevel Inheritance”

OR

Multilevel inheritance is a mechanism in which we derive (inherit) a class from another derived  class. We can give an example of grandfather – father- son relationship for exhibiting multilevel inheritance. Here the son may inherit the intelligence of the father and the color of the grandfather, further the son could be inherited.

 

   Class A

{


};

Class B: Public A

{


};

Class C: Public Bs

{


};

Example : Program to create a base class called grandfather and derive it too father class which in tern s derived to son class.

include<iostream.h>

#include <Conio.h>

class GrandFather

{

Private : char name[20];

int age;

Public : Char color[15];

void getdata();

void putdata();

};

class father: public GrandFather

{

private : char qualification;

float salary;

public : int IQ;

void read();

void print();

};

 

class son: public father

{

private : char hobby[20];

 

public : void input();

void output();

};

void GrandFather :: getdata()

{

Cout<<” Enter the name :”;

Cin>>name;

 

Cout<<” Enter the age :”;

Cin>>age;

 

Cout<<” Enter the color :”;

Cin>>color;

 

 

void GrandFather :: display()

{

cout <<“Name =”<<name<<endl;

cout <<“Age =”<<age<<endl;

cout <<“Color =”<<color<<endl;

 

}

void father :: read()

{

father:: getdata();

cout<<” Enter the qualification:”;

cin>>qualification;

cout<<” Enter the Salary:”;

cin>>salary;

cout<<” Enter the IQ:”;

cin>>IQ;

}

void Father :: print(void)

{

father :: display();

cout<<” qualification =”<<qualification<<endl;

cout<<” salary = “<<salary<<endl;

cout<<” IQ = “<<IQ<<endl;

}

void son :: input(void)

{

father::read();

cout<<“Enter the hobby:”;

cin>>hobby;

}

void son :: output(void)

{

father::print();

cout<<“hobby = “<<hobby<<endl;

}

void main()

{

son s1;

cout<<” Enter the son information…”<<endl;

s1.input();

cout<<“Son’s information is as fallows..”<<endl;

s1.output();

}

  1. Multiple Inheritance

A Derived class with  several base class is called is called “Multiple Inheritance”

OR

It is  a mechanism in which a new class is derived from several bas class. We can give an analogy of prime inheriting the kings intelligence and bravery and queens beauty .. multiple inheritance follows may-to-many relation.

The syntax for defining and declaring a derived class with multiple base classes is as fallows

Class D: Visibility Bc1, Visibility Bc2, …Visibility Bcn

{

}

Where class is a keyword

D= is the name of the derived class

Bc1, Bc2…Bcn= are the base classes, and must be separated by commas.

Visibility= is the visibility mode (Public//private)

Example:

Class prince:public king, public queen

{

Protected:char skill[20];

Public: void getskill(void)

Void putskill(void);

};

 

 

Class A1

{


};

Class A2

{


};

Class B : public A1, Public A2

{


};

  1. Hierarchical Inheritance:

On the other hand a single may be inherited by more then one class is known as “Hierarchical Inheritance”.

Class B1 : public A

{


};

Class B2 : public A

{


};

  1. Hybrid Inheritance

It is the mechanism in which two or more form of inheritance are used

Visibility Mode

A -> Base class

B-> Sub Class

It is a subclass and visibility mode is public

Class A : public B

{


};

The public member will be provided in B, and protected will protected.

It visibility mode is private then both protected and public member of A will be private member

Is a Relationship is always implements as a public inheritance

Constructor and Destructor in Inheritance First child class constructor will be rub during creation of object of child class, but as soon as object created child class constructor run and it will call constructor of its parent class and after the execution parent class constructor it will resume it constructor execution.

B  ( ) : A ( )

{

};

While in case of destructor first child destructor execute then parent destructor executed.

Inheritance and Constructor

When a base class with the constructor is inherited into a derived class, the derived class shares the base class constructor. There would derive a question reading which of the two constructor (one in the base class and another in the derived class). Is invoked first whenever we define an object in the derived class, the constructor of the base class invoked first and then the constructor of the derived class is called.

Example : program to illustrate the order of execution of constructor  in a class hierarchy

#include<iostream.h>

#include<conio.h>

class BC1

{

Protected : int i;

public : BC1()   // Base class constructor

{

i = 10;

cout<<“In base class : i=”<<endl;

}

};

class DC1 : public BC1

{

protected : int j;

public : DC1()

{

j = 20;

cout<<” In derived class : j=”<<endl;

}

};

void main()

{

DC1 d;

}

Output : In base class : i=10

In derived class : j=20

Inheritance and Destructor

Destructor can also be used in the inheritance hierarchy. If the  constructor are called down the line from the base to the derived class, the destructor are called just in the reverse order. That is from the derived class up to the base class

Example : Program to illustrate the order of execution  of destructor in a class hierarchy

#include<iostream.h>

#include<conio.h>

class BC1

{

Protectd : int i;

public : BC1()

{

i = 10;

cout<<“In bse class : i=”<<i<<endl;

}

~BC1()

{

cout<<“Destructor of BC1″<<endl;

};

class DC1 : public BC1

{

protected : int j;

public : DC1()

{

j = 20;

cout<<“Destructor of DC1 : j=”<<j<<endl;

}

~DC1()

{

cout<<“Destructor of DC1″<<endl;

};

class DC2 : public DC1

{

protected : int k;

public : DC2()

{

k = 30;

cout<<“Destructor of DC2 : k=”<<k<<endl;

}

~DC2()

{

cout<<“Destructor of DC2″<<endl;

};

 

 

void main()

{

DC2 d;

cout<<“\n”;

 

}

Output:

Constructor of BC1 : i = 10

Constructor of DC1 : j = 20

Constructor of DC2 : k = 30

 

Destructor of DC2

Destructor of DC1

Destructor of BC1

 

This Pointer

Every object in C++ has access to its own address through an important pointer called this pointer

Friend function doesn’t have a ‘this’ pointer between friends are not members of a class. Only member function have this pointer.

class Box

{

private:

int l, b, h;

public:

void set (int l, int b, int h)

{

this -> l = l;

this -> b = b;

this -> h = h;

}

};

int main()

{

Box b;

b.set(5, 10, 30);

}

Method Overriding

It is the redefinition of base class function in its derived class, with same return type and same parameters.

Write method overriding is achieved at compile time

class Car

{

private:

int gearno

public:

void change_gear(int gear)

{

gera++;

}

}

class sportscar : public car

{

void change_gear(int gear)

{

  • (gear>5)

gear++;

}

}

 

int main()

{

Sportscar sc;

sc.change_gear(4);

}

Function of Sports car class will be called : while calling Change_gear(). First in check if any fun with this name exist in set calling class other with it goes to base class.

It goes because Useful: like we have change_gear for all except one car which have unique method of gear change

Virtual Function

A virtual function is a member function which is declared with a ‘virtual’ keyword in the base class and redelcared (overridden) in  a derived class. When you refer to a object of derived class using pointer to a base class, you call a virtual function of that object and execute the derived class versions of the function.

They are used to achieve run time polymorphism.

Virtual function cannot be static and also cannot be friend function of another class

Compile_time(Early Binding) Vs Run_time(Late Binding)

class base

{

virtual void print()

{

cut<<” this is a base print”<<endl;

}

void show()

{

cout<<” base show fun”<<endl;

}

}

class Derived

{

public: void print()

{

cout<<” derived print”<<endl;

}

void show()

{

cout<<‘ derived show fun”<<endl;

}

}

int main()

{

base *bptr;

derived der;

bptr = Rder;

bptr -> prinit();

bptr -> show();

}

Output: Derived print

This base show fun

As during complier time bptr. Behavior judge an the base of which lass it belng, so bptr represent base class.

In the funtion is not virtual then it will allow binding at complier time and print fun of base class will get binded between bptr represent base lass

But t run time bptr points to the object to class derived, so it will define function of derived at run time.

Working of virtual function (VTable and Virtu)

If a class contains virtual function then complier it self does two things:

  1. A virtual (VPTR) is created every time object created for that class which contains virtual function.
  2. Irrespective of object is created or not static array of pointer called VTABLE where each cell point to each virtual function is created, in base class and derived class.

Sometimes implementation of al function cannot be provided in the base class. Such a class is called abstract class.

 

A pure virtual function in c++ is a virtual function for which we don’t have any implementation, we only declared it.

Class Test

{

Public :

Virtual void fun() =0;

}

  1. A lass is abstract it has at least one pure virtual function. We cannot declared object of abstract class

Ex: Test t; it will show error

  1. We can have pointer or references of abstract class.
  2. We can access the other function except virtual by object of its derived class.
  3. If we don’t override the pure virtual function in derived class then it becomes abstract.s
  4. An abstract class can have constructor(read from GFG)

Template in C++

Template < Class x>

{

If (a>b>

Return a;

Else

Return b;

}

It just  help in data type. So tat we can write generic function that can be used for different data type.

Dynamic Constructor

When allocation of memory is done dynamically using dynamic memory allocator ‘new’ in constructor.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Virtual destructor

Deleting a derived class object using a pointer base class that has a non-virtual destructor result in undefined behaviour. i.e

Destructor of base class runs only

Nested class

A nested class is a member and such has the same access rights as any other member.

The member of enclosing class have no such access to nested class, members

Class Enclosing

{

Private: int x;

Public: class Nested

{

Int y;

Void fun(int a)

{

X = a;

}

}

Void fun1 (int b)

{

Y=b;

}

}