>> jaise hum koi cheez google p search krte hain and google hume result deta hai to vo high level hota hai and jb hum google p andr dekhenge k vo result de kse rha hai kse kaam krra hai to vo low level khte hain.
similarly locgical things that we can do with computer is called high level language and jb programming language see hum hardware and memory ko control kr paae to use lowlevel language khte hain.
>> this is the extraction operator used in cin.
Pointers
Arrays
#include<iostream>
using namespace std;
int main(){
// Array Example
int marks[] = {23, 45, 56, 89};
int mathMarks[4];
mathMarks[0] = 2278;
mathMarks[1] = 738;
mathMarks[2] = 378;
mathMarks[3] = 578;
cout<<"These are math marks"<<endl;
cout<<mathMarks[0]<<endl;
cout<<mathMarks[1]<<endl;
cout<<mathMarks[2]<<endl;
cout<<mathMarks[3]<<endl;
// You can change the value of an array
marks[2] = 455;
cout<<"These are marks"<<endl;
// cout<<marks[0]<<endl;
// cout<<marks[1]<<endl;
// cout<<marks[2]<<endl;
// cout<<marks[3]<<endl;
for (int i = 0; i < 4; i++)
{
cout<<"The value of marks "<<i<<" is "<<marks[i]<<endl;
}
// Quick quiz: do the same using while and do-while loops?
// Pointers and arrays
int* p = marks;
cout<<*(p++)<<endl;
cout<<*(++p)<<endl;
// cout<<"The value of *p is "<<*p<<endl;
// cout<<"The value of *(p+1) is "<<*(p+1)<<endl;
// cout<<"The value of *(p+2) is "<<*(p+2)<<endl;
// cout<<"The value of *(p+3) is "<<*(p+3)<<endl;
return 0;
}
>>Structures, Union and enum
#include<iostream>
using namespace std;
typedef struct employee
{
/* data */
int eId; //4
char favChar; //1
float salary; //4
} ep;
union money
{
/* data */
int rice; //4
char car; //1
float pounds; //4
};
int main(){
enum Meal{ breakfast, lunch, dinner};
Meal m1 = lunch;
cout<<(m1==2);
// cout<<breakfast;
// cout<<lunch;
// cout<<dinner;
// union money m1;
// m1.rice = 34;
// m1.car = 'c';
// cout<<m1.car;
// ep harry;
// struct employee shubham;
// struct employee rohanDas;
// harry.eId = 1;
// harry.favChar = 'c';
// harry.salary = 120000000;
// cout<<"The value is "<<harry.eId<<endl;
// cout<<"The value is "<<harry.favChar<<endl;
// cout<<"The value is "<<harry.salary<<endl;
return 0;
}
>>Functions and their prototypes
#include<iostream>
using namespace std;
// Function prototype
// type function-name (arguments);
// int sum(int a, int b); //--> Acceptable
// int sum(int a, b); //--> Not Acceptable
int sum(int, int); //--> Acceptable
// void g(void); //--> Acceptable
void g(); //--> Acceptable
int main(){
int num1, num2;
cout<<"Enter first number"<<endl;
cin>>num1;
cout<<"Enter second number"<<endl;
cin>>num2;
// num1 and num2 are actual parameters
cout<<"The sum is "<<sum(num1, num2);
g();
return 0;
}
int sum(int a, int b){
// Formal Parameters a and b will be taking values from actual parameters num1 and num2.
int c = a+b;
return c;
}
void g(){
cout<<"\nHello, Good Morning";
}
>>Call by value and Call by Reference(using & and reference variable
Function Overloading (same name k functions bana kr diff kaam kara skte hain kuki jb function call hoga to vo sbse phle arguments dekhega kiitni hai .)
----------------------------------------------------------------------------
>> Static data member and methods(ek esa variable and method jo saare objects k liye same rahe change na ho)
static variable hmesha class k bahara initialize hoga and uski memory ek bar hi allocate hogi class ki memory k saath.
static varible by default 0 hoga.
static member funtion isliye banate hain k vo saare static data members and other static funtions ko access kr sake
ye function bss static data members and member funtion ko hi access kr skte hain aur kuch ni .
and ye funtion class k name and scope resolution operator (::) se hi access hota hai.
#include <iostream>
using namespace std;
class Employee
{
int id;
static int count;
public:
void setData(void)
{
cout << "Enter the id" << endl;
cin >> id;
count++;
}
void getData(void)
{
cout << "The id of this employee is " << id << " and this is employee number " << count << endl;
}
static void getCount(void){
// cout<<id; // throws an error
cout<<"The value of count is "<<count<<endl;
}
};
// Count is the static data member of class Employee
int Employee::count; // Default value is 0
int main()
{
Employee harry, rohan, lovish;
// harry.id = 1;
// harry.count=1; // cannot do this as id and count are private
harry.setData();
harry.getData();
Employee::getCount();
rohan.setData();
rohan.getData();
Employee::getCount();
lovish.setData();
lovish.getData();
Employee::getCount();
return 0;
}
>>Array of Objects
#include <iostream>
using namespace std;
class Employee
{
int id;
int salary;
public:
void setId(void)
{
salary = 122;
cout << "Enter the id of employee" << endl;
cin >> id;
}
void getId(void)
{
cout << "The id of this employee is " << id << endl;
}
};
int main()
{
// Employee harry, rohan, lovish, shruti;
// harry.setId();
// harry.getId();
Employee fb[4];
for (int i = 0; i < 4; i++)
{
fb[i].setId();
fb[i].getId();
}
return 0;
}
>>Passing Objects as Function Argument.
#include<iostream>
using namespace std;
class complex{
int a;
int b;
public:
void setData(int v1, int v2){
a = v1;
b = v2;
}
void setDataBySum(complex o1, complex o2){
a = o1.a + o2.a;
b = o1.b + o2.b;
}
void printNumber(){
cout<<"Your complex number is "<<a<<" + "<<b<<"i"<<endl;
}
};
int main(){
complex c1, c2, c3;
c1.setData(1, 2);
c1.printNumber();
c2.setData(3, 4);
c2.printNumber();
c3.setDataBySum(c1, c2);
c3.printNumber();
return 0;
}
>> Friend Funtions
#include<iostream>
using namespace std;
// 1 + 4i
// 5 + 8i
// -------
// 6 + 12i
class Complex{
int a, b;
friend Complex sumComplex(Complex o1, Complex o2);
public:
void setNumber(int n1, int n2){
a = n1;
b = n2;
}
// Below line means that non member - sumComplex funtion is allowed to do anything with my private parts (members)
void printNumber(){
cout<<"Your number is "<<a<<" + "<<b<<"i"<<endl;
}
};
Complex sumComplex(Complex o1, Complex o2){
//cout << a; it throws error because this funtion don't know what is a as it is not a member of class.
Complex o3;
o3.setNumber((o1.a + o2.a), (o1.b+o2.b));
return o3;
}
int main(){
Complex c1, c2, sum;
c1.setNumber(1, 4);
c1.printNumber();
c2.setNumber(5, 8);
c2.printNumber();
sum = sumComplex(c1, c2);
sum.printNumber();
return 0;
}
/* Properties of friend functions
1. Not in the scope of class
2. since it is not in the scope of the class, it cannot be called from the object of that class. c1.sumComplex() == Invalid
3. Can be invoked without the help of any object
4. Usually contains the objects as arguments
5. Can be declared inside public or private section of the class
6. It cannot access the members directly by their names and need object_name.member_name to access any member.
7. Friend funtion ki declaration inside class hum public mein yaa private mein kahin bhi de skte hain koi frk ni pdta.
*/
------------------------------------------------------------------------
#include <iostream>
using namespace std;
// Forward declaration
class Complex;
class Calculator
{
public:
int add(int a, int b)
{
return (a + b);
}
int sumRealComplex(Complex, Complex);
int sumCompComplex(Complex, Complex);
};
class Complex
{
int a, b;
// Individually declaring functions as friends
// friend int Calculator ::sumRealComplex(Complex, Complex);
// friend int Calculator ::sumCompComplex(Complex, Complex);
// Aliter: Declaring the entire calculator class as friend
friend class Calculator;
public:
void setNumber(int n1, int n2)
{
a = n1;
b = n2;
}
void printNumber()
{
cout << "Your number is " << a << " + " << b << "i" << endl;
}
};
int Calculator ::sumRealComplex(Complex o1, Complex o2)
{
return (o1.a + o2.a);
}
int Calculator ::sumCompComplex(Complex o1, Complex o2)
{
return (o1.b + o2.b);
}
int main()
{
Complex o1, o2;
o1.setNumber(1, 4);
o2.setNumber(5, 7);
Calculator calc;
int res = calc.sumRealComplex(o1, o2);
cout << "The sum of real part of o1 and o2 is " << res << endl;
int resc = calc.sumCompComplex(o1, o2);
cout << "The sum of complex part of o1 and o2 is " << resc << endl;
return 0;
}
-----------------------------------------------------------
#include<iostream>
using namespace std;
class Y;
class X{
int data;
public:
void setValue(int value){
data = value;
}
friend void add(X, Y);
};
class Y{
int num;
public:
void setValue(int value){
num = value;
}
friend void add(X, Y);
};
void add(X o1, Y o2){
cout<<"Summing data of X and Y objects gives me "<< o1.data + o2.num;
}
int main(){
X a1;
a1.setValue(3);
Y b1;
b1.setValue(15);
add(a1, b1);
return 0;
}
---------------------------------------------------------
#include<iostream>
using namespace std;
class c2;
class c1{
int val1;
friend void exchange(c1 & , c2 &);
public:
void indata(int a){
val1 = a;
}
void display(void){
cout<< val1 <<endl;
}
};
class c2{
int val2;
friend void exchange(c1 &, c2 &);
public:
void indata(int a){
val2 = a;
}
void display(void){
cout<< val2 <<endl;
}
};
/*
Trick to swap 2 numbers a and b:
temp = a;
a = b;
b = temp;
*/
void exchange(c1 &x, c2 &y){
int tmp = x.val1;
x.val1 = y.val2;
y.val2 = tmp;
}
int main(){
c1 oc1;
c2 oc2;
oc1.indata(34);
oc2.indata(67);
exchange(oc1, oc2);
cout<<"The value of c1 after exchanging becomes: ";
oc1.display();
cout<<"The value of c2 after exchanging becomes: ";
oc2.display();
return 0;
}
>>Constructors
#include <iostream>
using namespace std;
class Complex
{
int a, b;
public:
// Creating a Constructor
// Constructor is a special member function with the same name as of the class.
//It is used to initialize the objects of its class
//It is automatically invoked whenever an object is created
Complex(void); // Constructor declaration
void printNumber()
{
cout << "Your number is " << a << " + " << b << "i" << endl;
}
};
Complex ::Complex(void) // ----> This is a default constructor as it takes no parameters
{
a = 0;
b = 0;
// cout<<"Hello world";
}
int main()
{
Complex c1, c2, c3;
c1.printNumber();
c2.printNumber();
c3.printNumber();
return 0;
}
/* Characteristics of Constructors
1. It should be declared in the public section of the class
2. They are automatically invoked whenever the object is created
3. They cannot return values and do not have return types
4. It can have default arguments
5. We cannot refer to their address
*/
>>Paramerterized and Default Constructors.
#include<iostream>
using namespace std;
class Complex
{
int a, b;
public:
Complex(int, int); // Constructor declaration
void printNumber()
{
cout << "Your number is " << a << " + " << b << "i" << endl;
}
};
Complex ::Complex(int x, int y) // ----> This is a parameterized constructor as it takes 2 parameters
{
a = x;
b = y;
// cout<<"Hello world";
}
int main(){
// Implicit call
Complex a(4, 6);
a.printNumber();
// Explicit call
Complex b = Complex(5, 7);
b.printNumber();
return 0;
}
-----------------------------------------------------------------------
#include <iostream>
#include<math.h>
using namespace std;
class point{
int x, y;
public:
point(int a, int b){
x = a; y = b;
}
friend float distance(point, point);
};
float distance(point p1, point p2){
float p, q, r;
p = (p1.x - p2.x)*(p1.x - p2.x);
q = (p1.y - p2.y)*(p1.y - p2.y);
r = sqrt(p+q);
return r;
}
int main(){
point p1(1, 5);
point p2(1, 1);
float d;
d = distance(p1, p2);
cout << "Distance between point p1 and p2 is : " << d;
return 0;
}
>>Constructor Overloading
#include <iostream>
using namespace std;
class Complex
{
int a, b;
public:
Complex(){
a = 0;
b =0;
}
Complex(int x, int y)
{
a = x;
b = y;
}
Complex(int x){
a = x;
b = 0;
}
void printNumber()
{
cout << "Your number is " << a << " + " << b << "i" << endl;
}
};
int main()
{
Complex c1(4, 6);
c1.printNumber();
Complex c2(5);
c2.printNumber();
Complex c3;
c3.printNumber();
return 0;
}
>>Constructors with default arguments
#include<iostream>
using namespace std;
class Simple{
int data1;
int data2;
int data3;
public:
//agr hum koi b aur c k liye koi value pass ni krte argument k roop mein to vo b=9 and c = 8 ko hi apni
// value bana lega in short these values are default values of b and c.
Simple(int a, int b=9, int c=8){
data1 = a;
data2 = b;
data3 = c;
}
void printData();
};
void Simple :: printData(){
cout<<"The value of data1, data2 and data3 is "<<data1<<", "<< data2<<" and "<< data3<<endl;
}
int main(){
Simple s(12, 13);
s.printData();
return 0;
}
>>Dynamic initialization of objects
#include<iostream>
using namespace std;
class BankDeposit{
int principal;
int years;
float interestRate;
float returnValue;
public:
BankDeposit(){}
BankDeposit(int p, int y, float r); // r can be a value like 0.04
BankDeposit(int p, int y, int r); // r can be a value like 14
void show();
};
BankDeposit :: BankDeposit(int p, int y, float r)
{
principal = p;
years = y;
interestRate = r;
returnValue = principal;
for (int i = 0; i < y; i++)
{
returnValue = returnValue * (1+interestRate);
}
}
BankDeposit :: BankDeposit(int p, int y, int r)
{
principal = p;
years = y;
interestRate = float(r)/100;
returnValue = principal;
for (int i = 0; i < y; i++)
{
returnValue = returnValue * (1+interestRate);
}
}
void BankDeposit :: show(){
cout<<endl<<"Principal amount was "<<principal
<< ". Return value after "<<years
<< " years is "<<returnValue<<endl;
}
int main(){
BankDeposit bd1, bd2, bd3;
int p, y;
float r;
int R;
cout<<"Enter the value of p y and r"<<endl;
cin>>p>>y>>r;
bd1 = BankDeposit(p, y, r);
bd1.show();
cout<<"Enter the value of p y and R"<<endl;
cin>>p>>y>>R;
bd2 = BankDeposit(p, y, R);
bd2.show();
return 0;
}
>>Copy Constructor
#include<iostream>
using namespace std;
class Number{
int a;
public:
Number(){
a = 0;
}
Number(int num){
a = num;
}
// When no copy constructor is found, compiler supplies its own copy constructor
Number(Number &obj){
cout<<"Copy constructor called!!!"<<endl;
a = obj.a;
}
void display(){
cout<<"The number for this object is "<< a <<endl;
}
};
int main(){
Number x, y, z(45), z2;
x.display();
y.display();
z.display();
Number z1(z); // Copy constructor invoked
z1.display();
z2 = z; // Copy constructor not called
z2.display();
Number z3 = z; // Copy constructor invoked
z3.display();
// z1 should exactly resemble z or x or y
return 0;
}
>>Destructor
#include<iostream>
using namespace std;
// Destructor never takes an argument nor does it return any value
int count=0;
class num{
public:
num(){
count++;
cout<<"This is the time when constructor is called for object number"<<count<<endl;
}
~num(){
cout<<"This is the time when my destructor is called for object number"<<count<<endl;
count--;
}
};
int main(){
cout<<"We are inside our main function"<<endl;
cout<<"Creating first object n1"<<endl;
num n1;
{
cout<<"Entering this block"<<endl;
cout<<"Creating two more objects"<<endl;
num n2, n3;
cout<<"Exiting this block"<<endl;
}
cout<<"Back to main"<<endl;
return 0;
}
>>Inheritance and its different types







#include <iostream>
using namespace std;
// Base Class
class Employee
{
public:
int id;
float salary;
Employee(int inpId)
{
id = inpId;
salary = 34.0;
}
Employee() {}
};
// Derived Class syntax
/*
class {{derived-class-name}} : {{visibility-mode}} {{base-class-name}}
{
class members/methods/etc...
}
Note:
1. Default visibility mode is private
2. Public Visibility Mode: Public members of the base class becomes Public members of the derived class
3. Private Visibility Mode: Public members of the base class becomes Private members of the derived class
4. Private members are never inherited
5. In base class if we had made any parameterised constructor then it becomes necessary to make
default constructor otherwise the derieved class will through
error because uska constructor call ni ho paaega... kuki derieved class ka constructor call
hone se phle base class ka constructor call hota hai.
*/
// Creating a Programmer class derived from Employee Base class
class Programmer : public Employee
{
public:
int languageCode;
Programmer(int inpId)
{
id = inpId;
languageCode = 9;
}
void getData(){
cout<<id<<endl;
}
};
int main()
{
Employee harry(1), rohan(2);
cout << harry.salary << endl;
cout << rohan.salary << endl;
Programmer skillF(10);
cout << skillF.languageCode<<endl;
cout << skillF.id<<endl;
skillF.getData();
return 0;
}
>>Single Inheritance Deep Dive
#include <iostream>
using namespace std;
class Base
{
int data1; // private by default and is not inheritable
public:
int data2;
void setData();
int getData1();
int getData2();
};
void Base :: setData(void)
{
data1 = 10;
data2 = 20;
}
int Base::getData1()
{
return data1;
}
int Base::getData2()
{
return data2;
}
class Derived : public Base
{ // Class is being derived publically
int data3;
public:
void process();
void display();
};
void Derived ::process()
{
data3 = data2 * getData1();
}
void Derived ::display()
{
cout << "Value of data 1 is " << getData1() << endl;
cout << "Value of data 2 is " << data2 << endl;
cout << "Value of data 3 is " << data3 << endl;
}
int main()
{
Derived der;
der.setData();
der.process();
der.display();
return 0;
}
>>Protected Access Modifier
#include<iostream>
using namespace std;
class Base{
protected:
int a;
private:
int b;
};
/*
For a protected member:
Public derivation Private Derivation Protected Derivation
1. Private members Not Inherited Not Inherited Not Inherited
2. Protected members Protected Private Protected
3. Public members Public Private Protected
*/
class Derived: protected Base{
};
int main(){
Base b;
Derived d;
// cout<<d.a; // Will not work since a is protected in both base as well as derived class
return 0;
}
>>Multilevel Inheritance]
#include <iostream>
using namespace std;
class Student
{
protected:
int roll_number;
public:
void set_roll_number(int);
void get_roll_number(void);
};
void Student ::set_roll_number(int r)
{
roll_number = r;
}
void Student ::get_roll_number()
{
cout << "The roll number is " << roll_number << endl;
}
class Exam : public Student
{
protected:
float maths;
float physics;
public:
void set_marks(float, float);
void get_marks(void);
};
void Exam ::set_marks(float m1, float m2)
{
maths = m1;
physics = m2;
}
void Exam ::get_marks()
{
cout << "The marks obtained in maths are: " << maths << endl;
cout << "The marks obtained in physics are: " << physics << endl;
}
class Result : public Exam
{
float percentage;
public:
void display_results()
{
get_roll_number();
get_marks();
cout << "Your result is " << (maths + physics) / 2 << "%" << endl;
}
};
int main()
{
/*
Notes:
If we are inheriting B from A and C from B:[ A--->B--->C ]
1. A is the base class for B and B is the base class for C
2. A-->B-->C is called Inheritance Path
*/
Result harry;
harry.set_roll_number(420);
harry.set_marks(94.0, 90.0);
harry.display_results();
return 0;
}
>>Multiple Inhertance
#include <iostream>
using namespace std;
// Syntax for inheriting in multiple inheritance
// class DerivedC: visibility-mode base1, visibility-mode base2
// {
// Class body of class "DerivedC"
// };
class Base1{
protected:
int base1int;
public:
void set_base1int(int a)
{
base1int = a;
}
};
class Base2{
protected:
int base2int;
public:
void set_base2int(int a)
{
base2int = a;
}
};
class Base3{
protected:
int base3int;
public:
void set_base3int(int a)
{
base3int = a;
}
};
class Derived : public Base1, public Base2, public Base3
{
public:
void show(){
cout << "The value of Base1 is " << base1int<<endl;
cout << "The value of Base2 is " << base2int<<endl;
cout << "The value of Base3 is " << base3int<<endl;
cout << "The sum of these values is " << base1int + base2int + base3int << endl;
}
};
/*
The inherited derived class will look something like this:
Data members:
base1int --> protected
base2int --> protected
Member functions:
set_base1int() --> public
set_base2int() --> public
set_show() --> public
*/
int main()
{
Derived harry;
harry.set_base1int(25);
harry.set_base2int(5);
harry.set_base3int(15);
harry.show();
return 0;
}
>>Ambiguity in Inheritance
#include<iostream>
using namespace std;
class Base1{
public:
void greet(){
cout<<"How are you?"<<endl;
}
};
class Base2{
public:
void greet()
{
cout << "Kaise ho?" << endl;
}
};
class Derived : public Base1, public Base2{
int a;
public:
void greet(){
Base2 :: greet();
}
};
class B{
public:
void say(){
cout<<"Hello world"<<endl;
}
};
class D: public B{
int a;
// D's new say() method will override base class's say() method
public:
void say()
{
cout << "Hello my beautiful people" << endl;
}
};
int main(){
// Ambibuity 1
// Base1 base1obj;
// Base2 base2obj;
// base1obj.greet();
// base2obj.greet();
// Derived d;
// d.greet();
// Ambiguity 2
B b;
b.say();
D d;
d.say();
return 0;
}
>>Virtual Base Class
Upr waali pic mein class A se 'a' naam ka object class B and C mein jaaega aur uske baad jb vo class D mein jaaega to Ambigiuity aa jaaegi because 'a' 2 jgah se aara hai and class D ko smj ni aaega kaunsa waala 'a' lena hai .
Isko solve krne k liye virtual base class banate hain
for example jb hum class B and c ko ingeritre krenge to class A ki visiblity mode k phle virtual laga denge jisse class A virtual class bn jaaegi
jo k a ko ek hi baar copy kregi baaki saari classes mein jisse Ambiguity solve ho jaaegi.
#include<iostream>
using namespace std;
/*
Inheritance:
student -->test [Done]
student-->sports [Done]
test --> result [Done]
sports --> result [Done]
*/
class Student{
protected:
int roll_no;
public:
void set_number(int a){
roll_no = a;
}
void print_number(void){
cout<<"Your roll no is "<< roll_no<<endl;
}
};
class Test : public virtual Student{
protected:
float maths, physics;
public:
void set_marks(float m1, float m2){
maths = m1;
physics = m2;
}
void print_marks(void){
cout << "You result is here: "<<endl
<< "Maths: "<< maths<<endl
<< "Physics: "<< physics<<endl;
}
};
class Sports: virtual public Student{
protected:
float score;
public:
void set_score(float sc){
score = sc;
}
void print_score(void){
cout<<"Your PT score is "<<score<<endl;
}
};
class Result : public Test, public Sports{
private:
float total;
public:
void display(void){
total = maths + physics + score;
print_number();
print_marks();
print_score();
cout<< "Your total score is: "<<total<<endl;
}
};
int main(){
Result harry;
harry.set_number(4200);
harry.set_marks(78.9, 99.5);
harry.set_score(9);
harry.display();
return 0;
}
#include<iostream>
using namespace std;
class b {
public:
int a = 10;
void sqr(){
a *= a;
}
};
class c {
public :
int a = 20;
void cube(){
a *= a;
}
};
class d :virtual public b, virtual public c{
public:
void print(){
cube();
sqr();
cout << c::a << endl;
cout << b::a;
}
};
int main(){
d obj;
obj.print();
}
#include <iostream>
#include <cmath>
using namespace std;
class SimpleCalculator {
int a, b;
public:
void getDataSimple()
{
cout<<"Enter the value of a"<<endl;
cin>>a;
cout<<"Enter the value of b"<<endl;
cin>>b;
}
void performOperationsSimple(){
cout<<"The value of a + b is: "<<a + b<<endl;
cout<<"The value of a - b is: "<<a - b<<endl;
cout<<"The value of a * b is: "<<a * b<<endl;
cout<<"The value of a / b is: "<<a / b<<endl;
}
};
class ScientificCalculator{
int a, b;
public:
void getDataScientific()
{
cout << "Enter the value of a" << endl;
cin >> a;
cout << "Enter the value of b" << endl;
cin >> b;
}
void performOperationsScientific()
{
cout << "The value of cos(a) is: " << cos(a) << endl;
cout << "The value of sin(a) is: " << sin(a) << endl;
cout << "The value of exp(a) is: " << exp(a) << endl;
cout << "The value of tan(a) is: " << tan(a) << endl;
}
};
class HybridCalculator : public SimpleCalculator, public ScientificCalculator{
};
int main()
{
HybridCalculator calc;
calc.getDataScientific();
calc.performOperationsScientific();
calc.getDataSimple();
calc.performOperationsSimple();
return 0;
}
>>COnstructors in Derived Class



#include<iostream>
using namespace std;
/*
Case1:
class B: public A{
// Order of execution of constructor -> first A() then B()
};
Case2:
class A: public B, public C{
// Order of execution of constructor -> B() then C() and A()
};
Case3:
class A: public B, virtual public C{
// Order of execution of constructor -> C() then B() and A()
};
*/
class Base1{
int data1;
public:
Base1(int i){
data1 = i;
cout<<"Base1 class constructor called"<<endl;
}
void printDataBase1(void){
cout<<"The value of data1 is "<<data1<<endl;
}
};
class Base2{
int data2;
public:
Base2(int i){
data2 = i;
cout << "Base2 class constructor called" << endl;
}
void printDataBase2(void){
cout << "The value of data2 is " << data2 << endl;
}
};
class Derived: public Base2, public Base1{
int derived1, derived2;
public:
Derived(int a, int b, int c, int d) : Base2(b), Base1(a)
{
derived1 = c;
derived2 = d;
cout<< "Derived class constructor called"<<endl;
}
void printDataDerived(void)
{
cout << "The value of derived1 is " << derived1 << endl;
cout << "The value of derived2 is " << derived2 << endl;
}
};
int main(){
Derived harry(1, 2, 3, 4);
harry.printDataBase1();
harry.printDataBase2();
harry.printDataDerived();
return 0;
}
>>Initialization List in constructors
#include <iostream>
using namespace std;
/*
Syntax for initialization list in constructor:
constructor (argument-list) : initilization-section
{
assignment + other code;
}
class Test{
int a;
int b;
public:
Test(int i, int j) : a(i), b(j){constructor-body}
};
*/
class Test
{
int a;
int b;
public:
// Test(int i, int j) : a(i), b(j)
// Test(int i, int j) : a(i), b(i+j)
// Test(int i, int j) : a(i), b(2 * j)
// Test(int i, int j) : a(i), b(a + j)
// Test(int i, int j) : b(j), a(i+b) -->RED Flag this will create problems because a will be initialized first
Test(int i, int j)
{
a = i;
b = j;
cout << "Constructor executed"<<endl;
cout << "Value of a is "<<a<<endl;
cout << "Value of b is "<<b<<endl;
}
};
int main()
{
Test t(4, 6);
return 0;
}
>>new and delete keyword in Pointers
#include<iostream>
using namespace std;
int main(){
// Basic Example
int a = 4;
int* ptr = &a;
*ptr = 999;
cout<<"The value of a is "<<*(ptr)<<endl;
// new operator
// int *p = new int(40);
float *p = new float(40.78);
cout << "The value at address p is " << *(p) << endl;
int *arr = new int[3];
arr[0] = 10;
*(arr+1) = 20;
arr[2] = 30;
// delete[] arr;
cout << "The value of arr[0] is " << arr[0] << endl;
cout << "The value of arr[1] is " << arr[1] << endl;
cout << "The value of arr[2] is " << arr[2] << endl;
// delete operator
return 0;
}
>>Pointers to object and Arrow operator
#include<iostream>
using namespace std;
class Complex{
int real, imaginary;
public:
void getData(){
cout<<"The real part is "<< real<<endl;
cout<<"The imaginary part is "<< imaginary<<endl;
}
void setData(int a, int b){
real = a;
imaginary = b;
}
};
int main(){
// Complex c1;
// Complex *ptr = &c1;
Complex *ptr = new Complex;
// (*ptr).setData(1, 54); is exactly same as
ptr->setData(1, 54);
// (*ptr).getData(); is as good as
ptr->getData();
// Array of Objects
Complex *ptr1 = new Complex[4];
ptr1->setData(1, 4);
ptr1->getData();
return 0;
}
>>Array of objects using pointers
#include<iostream>
using namespace std;
class ShopItem
{
int id;
float price;
public:
void setData(int a, float b){
id = a;
price = b;
}
void getData(void){
cout<<"Code of this item is "<< id<<endl;
cout<<"Price of this item is "<<price<<endl;
}
};
// 1 2 3
// ^
// |
// |
// ptr
// ptrTemp
int main(){
int size = 3;
// int *ptr = &size;
// int *ptr = new int [34];
// 1. general store item
// 2. veggies item
// 3. hardware item
ShopItem *ptr = new ShopItem [size];
ShopItem *ptrTemp = ptr;
int p, i;
float q;
for (i = 0; i < size; i++)
{
cout<<"Enter Id and price of item "<< i+1<<endl;
cin>>p>>q;
// (*ptr).setData(p, q);
ptr->setData(p, q);
ptr++;
}
for (i = 0; i < size; i++)
{
cout<<"Item number: "<<i+1<<endl;
ptrTemp->getData();
ptrTemp++;
}
return 0;
}
>>this pointer in C++
#include<iostream>
using namespace std;
class A{
int a;
public:
// A & setData(int a){
A& setData(int a){
this->a = a;
return *this;
}
void getData(){
cout<<"The value of a is "<<a<<endl;
}
};
int main(){
// this is a keyword which is a pointer which points to the object which invokes the member function
// in other words this keyword uss object ko point krta hai jisne yha p setdata() yaa aur kisi member funtion ko call kia hai
A a;
a.setData(4).getData();
return 0;
}
>>Polymorphism
// Polymorphism
// - one name and multiple forms
// - eg. Function overloading, operator overloading
// - eg. Virtual Functions
/*
Polymorphism in C++ can be of two types:
1. Compile time polymorphism(Static or Early Binding)
Compile-time polymorphism in C++ is achieved using:
1.1 - Function overloading
1.2 - Operator Overloading
2. Run time polymorphism(Dynamic or late Binding)
Run time polymorphism in C++ is achieved using:
2.1 - Virtual functions
>>Pointers to Derived class and Virtual funtions
#include<iostream>
using namespace std;
class BaseClass{
public:
int var_base;
void display(){
cout<<"Dispalying Base class variable var_base "<<var_base<<endl;
}
};
class DerivedClass : public BaseClass{
public:
int var_derived;
void display(){
cout<<"Dispalying Base class variable var_base "<<var_base<<endl;
cout<<"Dispalying Derived class variable var_derived "<<var_derived<<endl;
}
};
/*
1. agr base class k pointer derieved class k object ko point krta hai
to jo data member and functions base class mein hain whi access kr skte hain.
2. agr derieved class ka pointer base class k object ko point kre to error show hoga
3. jaise k hm main funtion mein dekh skte hain
jb base class ka pointer derieved class k object ko point krta hai to display base waala call hota hai
and
jb derieved class ka pointer derieved class k object ko point krta hai to display() fn derieved waala hi call
hota hai.
isko hi run time polymorphism khte hain kuki ye run time me decide hora hai k kaunsa funtion bind hoga.
4. now jb hum base class pointer use krre hain point krne k liye derieved class k object ko tb hume base class waala display
use ni krna hai but derieved class waala hi display hi use krna hai to base class waale funtion ko virtual bana do
isse hoga ye k run time mein jb binding hori hogi to compiler derieved class waale funtion k address ko bind krega and vo run ho jaaega.
5. agr derieved class ka pointer derieved class k object ko hi point krra hai and derieved class waale display ko virtual krdia
phir bhi derieved class waala display hi run hoga.
*/
int main(){
BaseClass * base_class_pointer;
BaseClass obj_base;
DerivedClass obj_derived;
base_class_pointer = &obj_derived; // Pointing base class pointer to derived class
base_class_pointer->var_base = 34;
// base_class_pointer->var_derived= 134; // Will throw an error
base_class_pointer->display();
base_class_pointer->var_base = 3400;
base_class_pointer->display();
DerivedClass * derived_class_pointer;
derived_class_pointer = &obj_derived;
derived_class_pointer->var_base = 9448;
derived_class_pointer->var_derived = 98;
derived_class_pointer->display();
// DerivedClass * p; //will show error
// p = &obj_base;
// p->var_base = 90;
// p->display();
return 0;
}
>>Rules of Virtual function
/*
Rules for virtual functions
1. They cannot be static
2. They are accessed by object pointers
3. Virtual functions can be a friend of another class
4. A virtual function in the base class might not be used.
5. If a virtual function is defined in a base class, there is no necessity of redefining it in the derived class.
mtlb agr yha iss code mein agr CWHVideo ka display function nahi hota to base class waala virtual display run
hojata.
*/
#include<iostream>
using namespace std;
class CWH{
protected:
string title;
float rating;
public:
CWH(string s, float r){
title = s;
rating = r;
}
virtual void display(){}
};
class CWHVideo: public CWH
{
float videoLength;
public:
CWHVideo(string s, float r, float vl): CWH(s, r){
videoLength = vl;
}
void display(){
cout<<"This is an amazing video with title "<<title<<endl;
cout<<"Ratings: "<<rating<<" out of 5 stars"<<endl;
cout<<"Length of this video is: "<<videoLength<<" minutes"<<endl;
}
};
class CWHText: public CWH
{
int words;
public:
CWHText(string s, float r, int wc): CWH(s, r){
words = wc;
}
void display(){
cout<<"This is an amazing text tutorial with title "<<title<<endl;
cout<<"Ratings of this text tutorial: "<<rating<<" out of 5 stars"<<endl;
cout<<"No of words in this text tutorial is: "<<words<<" words"<<endl;
}
};
int main(){
string title;
float rating, vlen;
int words;
// for Code With Harry Video
title = "Django tutorial";
vlen = 4.56;
rating = 4.89;
CWHVideo djVideo(title, rating, vlen);
// for Code With Harry Text
title = "Django tutorial Text";
words = 433;
rating = 4.19;
CWHText djText(title, rating, words);
CWH* tuts[2];
tuts[0] = &djVideo;
tuts[1] = &djText;
tuts[0]->display();
tuts[1]->display();
return 0;
}
>>Abstract Base Class and Pure Virtual Functions
/*
Pure Virtual Functions in C++
Pure virtual function is a function that doesn’t perform any operation and the function
is declared by assigning the value 0 to it. Pure virtual functions are declared in abstract base classes.
Abstract Base Class in C++
Abstract base class is a class that has at least one pure virtual function in its body.
The classes which are inheriting the base class must need to override the pure virtual function of the abstract
class otherwise the compiler will throw an error.
*/
#include<iostream>
using namespace std;
class CWH{
protected:
string title;
float rating;
public:
CWH(string s, float r){
title = s;
rating = r;
}
// this is called pure virtual function jo kuch krta ni hai but isliye hai kuki isko un classes mein
// define kia jaaega jo is CWH class se inherite hongi. and yhan ye CWH class Abstract Base class hai.
virtual void display()=0;
};
class CWHVideo: public CWH
{
float videoLength;
public:
CWHVideo(string s, float r, float vl): CWH(s, r){
videoLength = vl;
}
void display(){
cout<<"This is an amazing video with title "<<title<<endl;
cout<<"Ratings: "<<rating<<" out of 5 stars"<<endl;
cout<<"Length of this video is: "<<videoLength<<" minutes"<<endl;
}
};
class CWHText: public CWH
{
int words;
public:
CWHText(string s, float r, int wc): CWH(s, r){
words = wc;
}
void display(){
cout<<"This is an amazing text tutorial with title "<<title<<endl;
cout<<"Ratings of this text tutorial: "<<rating<<" out of 5 stars"<<endl;
cout<<"No of words in this text tutorial is: "<<words<<" words"<<endl;
}
};
int main(){
string title;
float rating, vlen;
int words;
// for Code With Harry Video
title = "Django tutorial";
vlen = 4.56;
rating = 4.89;
CWHVideo djVideo(title, rating, vlen);
// for Code With Harry Text
title = "Django tutorial Text";
words = 433;
rating = 4.19;
CWHText djText(title, rating, words);
CWH* tuts[2];
tuts[0] = &djVideo;
tuts[1] = &djText;
tuts[0]->display();
tuts[1]->display();
return 0;
}
>>File I/O
The file is a patent of data that is stored in the disk. Anything written inside the file is called a patent, for example: “#include” is a patent. The text file is the combination of multiple types of characters, for example, semicolon “;” is a character.
The computer read these characters in the file with the help of the ASCII code. Every character is mapped on some decimal number. For example, the ASCII code for the character “A” is “65” which is a decimal number. These decimal numbers are converted into a binary number to make them readable for the computer because the computer can only understand the language of “0” and “1”.
The reason that computers can only understand binary numbers is that a computer is made up of switches and switches only perform two operations “true” or “false”.
File Input and Output in C++
The file can be of any type whether it is a file of a C++ program, a file of a game, or any other type of file. There are two main operations that can be performed on files
An image is shown below to show the process of file read and write.
Figure 1: File Read and Write Diagram
As shown in figure 1,
- The user can provide input to the C++ program by using the keyboard through the “cin>>” keyword
- The user can get output from the C++ program on the monitor through the “cout<<” keyword
- The user can write on the file
- The user can read the file
>>File reading and writing
These are some useful classes for working with files in C++
- fstreambase
- ifstream --> derived from fstreambase
- ofstream --> derived from fstreambase
In order to work with files in C++, you will have to open it. Primarily, there are 2 ways to open a file:
- Using the constructor
- Using the member function open() of the class
An example program is shown below to demonstrate the concept of reading and writing files
Code Snippet 1: Writing Files Example Program
As shown in a code snippet 1,
- We have created a string “st” which has a value “harry Bhai”
- Object “out” is created of the type ofstream and the file “sample60.txt” is passed to it
- The string “st” is passed to object “out”
The output of the following program is shown in figure 1
Figure 1: Writing File Operation Output
Code Snippet 2: Reading Files Example Program
As shown in a code snippet 1,
- We have created a string “st2” which is empty
- We have made a text file “sample60b.txt” and written “This is coming from a file” in it
- Object “in” is created of the type instream and the file “sample60b.txt” is passed to it
- The function “getline” is called and the object “in” and the string “st2” are passed to it. The main thing to note here is that the function “getline” is used when we want to read the whole line
- String “st2” is printed
The output of the following program is shown in figure 2
>>FIle Read and Write in Same Program and Closing File
#include<iostream>
#include<fstream>
using namespace std;
int main(){
string s, t;
// getline se multiword string input le skte hain.
cout << "Enter Your name : ";
getline(cin, s);
ofstream write("11.txt");
write << s + " is my name.\n";
// jb read yaa write operation perform kr lo to file ko close kr dete hain.
// isse agr usi file ko read krna hoga phrse to kr skte hain agr ye use ni kia to ek hi file ko read write ni kr skte.
write.close();
ifstream read("11.txt");
getline(read, t);
cout << t;
read.close();
return 0;
}
>>File I/O open() and eof() functions
#include<iostream>
#include<fstream>
using namespace std;
int main(){
string s, t, u;
// getline se multiword string input le skte hain.
cout << "Enter Your name : ";
getline(cin, s);
// opening file using constructor
ofstream write("11.txt");
write << s + " is my name.\n";
write << "What is your name?\n";
write << "HUH?";
// jb read yaa write operation perform kr lo to file ko close kr dete hain.
// isse agr usi file ko read krna hoga phrse to kr skte hain agr ye use ni kia to ek hi file ko read write ni kr skte.
write.close();
ifstream read;
// opening file using open() function
read.open("11.txt");
// below lines print first and second letter of the first line.
// read >> t; read >> u;
// cout << t + u;
// to read all the data which is in file use while loop.
// while loop k andr ka statement ye bol rha hai k jbtk end of file is false tbtk while loop chalate rho.
while(read.eof() == 0){
getline(read, t);
cout << t << endl;
}
read.close();
return 0;
}
>>Templates
// template is nothing but it creates class with the data member we want
// jaise humne float datatype template mein pass kia to float ka class bana dena
// iss program mein jahan jahan T likha hoga uske jgah vo data type laga dega.
// this is very important in competitive coding and it saves time.
#include<iostream>
using namespace std;
template <class T>
class vector{
T *arr;
int size;
T d = 0;
public:
vector(int n) : size(n){
arr = new T[size];
}
void getdata(){
cout << "Enter values in vector : ";
for(int i = 0; i < size; i++){
cin >> arr[i];
}
}
T dotproduct(vector &v){
for(int i = 0; i < size; i++){
d += this->arr[i] * v.arr[i];
}
return d;
}
};
int main(){
vector<float> v1(3);
v1.getdata();
vector<float> v2(3);
v2.getdata();
float ans;
ans = v2.dotproduct(v1);
cout << "Dot product is : " << ans;
return 0;
}
>>Template with multiple arguments and default arguments
// template here have multiple argument or it takes multiple datatype as an argument.
#include<iostream>
using namespace std;
// isme maine default argument passs kia hai isse hoga ye k agr maine obj bnate wkt koi data member ni dia as a argument
// to ye default argument use ho jaaenge aur agr datatype de dia to default na use hokr jo dia hai vo use ho jaaega.
template <class T1 = int, class T2 = float, class T3 = char>
class data{
T1 a;
T2 b;
T3 c;
public:
data(T1 x, T2 y, T3 z) : a(x), b(y), c(z){}
void putdata(){
cout << "T1 : " << a << endl;
cout << "T2 : " << b << endl;
cout << "T3 : " << c << endl;
}
};
int main(){
data<char, char, float> obj('P', 'c', 1.5);
obj.putdata();
cout << endl;
data<> obj1(1, 3.4, 's');
obj1.putdata();
return 0;
}
>>Function Template with arguments
#include<iostream>
using namespace std;
template<class T1, class T2>
float avg(T1 a, T2 b){
float x;
x = (a+b)/2.0;
return x;
}
int main(){
float l;
l = avg(2.4, 4);
cout << l;
return 0;
}
>>Defining member function outside template and overloading template functions
#include<iostream>
using namespace std;
// ---------------------------------------------------------------------------------------
// ye template bss isliye banaya hai taaki ye bata sake k template k andr k
// member function ko class k bhrr kse define krte hain.
template<class T>
class data{
T d;
public:
data(T x):d(x){}
void putdata();
};
template<class T>
void data<T> :: putdata(){
cout << "The value of d is : "<< d << endl;
}
// ----------------------------------------------------------------------------------------
void func(int q){
cout << "In func which is not templatised : " << q << endl;
}
template<class C>
void func(C q){
cout << "In func which is templatised : " << q << endl;
}
int main(){
// for defining member function outside the class
data<char> obj('p');
obj.putdata();
// ye func isliye banaya hai taaki bata paae k templatised function se jyada priority
// not templatised function ko milti hai.
func(3);
return 0;
}
>>Standard Template Library(STL)

RA = random access
>>Vectors
#include<iostream>
#include<vector>
using namespace std;
void display(vector<int> &v){
for (int i = 0; i < v.size(); i++)
{
cout << v.at(i) << "\t";
}
}
int main(){
// diff ways to declare vector
// zero length integer vector.
vector<int> v1;
// 4-element integer vector.
vector<int> v2(4);
// same as v2 4-element integer array
vector<int> v3(v2);
// 4-element vector in f's. iske container mein 4 char ka space hota hai and sbme 'f' stored hota hai.
vector<char> v4(4, 'f');
int size, element;
cout << "Enter size of an array : ";
cin >> size;
for (int i = 0; i < size; i++){
cout << "Enter vector element number " << (i+1) << " : ";
cin >> element;
// baki sb element ko ek step back push kr deta hai and element ko last mein add kr deta hai.
v1.push_back(element);
}
// // pops out last object
// v1.pop_back();
// it makes and iterator which points to the first object of tha container.
vector<int> :: iterator iter = v1.begin();
// it inserts value 69 in container 5 times at the postion first.
// agr insert mein iter ki jgha iter+1 use krlia to vo postion 2 p same result print kr dega.
v1.insert(iter+2, 5, 69);
display(v1);
return 0;
}
>>List
#include<iostream>
#include<list>
using namespace std;
void display(list<int> &ls){
list<int> :: iterator it;
for (it = ls.begin(); it != ls.end(); it++){
cout << *it << " ";
}
cout << endl;
}
int main(){
// empty list of 0 length.
list<int> l1;
for (int i = 0; i < 3; i++){
l1.push_front((i+1)*2);
}
l1.push_back(2);
l1.sort();
cout << "List 1 : ";
display(l1);
// // jitni jgah bhi 2 hoga list mein vo remove ho jaaega remove function se.
// l1.remove(2);
// display(l1);
// empty list of length 4
list<int> l2(4);
list<int> :: iterator ite;
ite = l2.begin();
*ite = 45;
ite++;
*ite = 5;
ite++;
*ite = 4;
ite++;
*ite = 78;
ite++;
l2.sort();
cout << "List 2 : ";
display(l2);
cout << "Merged List : ";
l1.merge(l2);
display(l1);
cout << "Reverse of Merged List : ";
l1.reverse();
display(l1);
return 0;
}
>>Map
#include<iostream>
#include<map>
#include<iomanip>
using namespace std;
int main(){
map<string, int> m1;
// map is like dictionary in python here name is key and marks are value of it.
m1["Priyansh"] = 95;
m1["pratik"] = 73;
m1["Akshita"] = 35;
m1["Ritanshu"] = 45;
m1.insert({{"Akash", 24}, {"Sneha", 65}});
map<string, int> :: iterator it;
for (it = m1.begin(); it != m1.end(); it++){
cout << setw(8)<< (*it).first << " |" << setw(5)<< (*it).second << endl;
}
return 0;
}
>>Function object
#include<iostream>
#include<algorithm>
#include<functional>
using namespace std;
int main(){
// Function Objects(Functor) : Function wrapped in a class so that it is available like an object.
int arr[] = {1, 6, 4, 36, 5, 4, 96, 7, 0};
// by default it sorts in ascending order.
sort(arr, arr+9);
for (int i = 0; i < 9; i++){
cout << arr[i] << " ";
}
cout << endl;
// if we pass greaterfunctor then it will sort in descending order.
sort(arr, arr+9, greater<int>());
for (int i = 0; i < 9; i++){
cout << arr[i] << " ";
}
return 0;
}
<>Operator overloading,
Comments
Post a Comment