Topics
Topics
Topics
#include<iostream>
int main()
cout<<”Hello World”;
return 0;
Here, iostream is the header file which is important for the cpp programs to
perform input, output and many other operations , and it is added to the
program by including it using #include.
main() is the starting function and ‘int’ denotes its return type i.e. Integer. Cpp
doesn’t consist of “void main()”.
If the line “using namespace std;” is not specified, then we should use the
methods with “std” explicitly, e.g. std::cout<<”Hello world!”;
Comments are strings to provide more info. about any block of code.
Variable Declaration Syntax :
OR
Datatype variable_name;
Types of Comments
Datatypes in C++
1)Primitive/Primary/Built-in Datatypes
signed ( 4 bytes ) : Can be used with char, int, float & double. ((+,-) values)
unsigned ( 4 bytes ) : Can be used with char, int, float & double. (+ values only)
2)Non-Primitive/Secondary/User-defined Datatypes
3)Derived Datatypes
Scope of Variables
Global Scope : Throughout the program, within all the block of codes.
Note : We can have the local and global variables with same name, but it can
create confusion sometimes. Also, whenever called in the function or any block
of code, the local variable will be considered for use and the global variables
value will be ignored. So it is recommended to create global and local variables
with different names. But if we want to access the global variable value then
we use the scope resolution operator i.e. ( :: ) e.g. ::variable_name.
Input Stream : Direction of flow of bytes takes place from input device (e.g.
keyboard) to the main memory.
Output Stream : Direction of flow of bytes takes place from main memory to
the output device (e.g. Display)
#include<iostream>
using namespace std;
int main()
{
int num1, num2;
cout<<"Enter the value of num1 : \n";
cin>>num1;
#include<iostream>
NOTE : Refer “cppreference.com” for knowing all system header files and
other stuff related to C++
#include “filename.extension”
Operators in C++
Arithmetic Operators ( +, -, *, /, % )
Assignment Operators ( Simple : (=) , Compound : (+=, -=, *=, /=, %=) )
Bitwise Operator ( &, |, ^ (XOR), << (L Shift), >> (R Shift), ~ (One’s Compliment))
e.g. Below both x and y will have the same value. Address of x and y is same.
float x = 123;
float & y = x;
Here, x and y are the same variable but with two different names, y is not the
copy of the x. They both have the same address.
Typecasting in C++
e.g. Use datatypes within brackets i.e. (datatype) to typecast the variable.
Constants are the values which can’t be changed. We use the ‘const’ keyword
to create a constant variable.
e.g. Here, ‘var’ is a constant and its value cannot be changed in the program.
Manipulators are the keywords or characters which helps to format your data
display or decide how the data/information should be printed or displayed.
There are many manipulators but two are mostly used:
The header file “iomanip” consist of several manipulators and the setw()
manipulator is also provided by the “iomanip” header file. Therefore to use
setw() we need to include the “iomanip” header file.
The precedence is the power of the operators to get resolved first. The
precedence of the operators is as below:
Associativity lies when the operators has the same precedence, for e.g. ( +, - ).
The associativity may flow from left-to-right direction or vice versa, therefore
the operators with same precedence are resolved as per their occurrences
from left to right or right to left depending on to their associativity. The ( +, - )
operators have the associativity from left to right.
Pointers in C++ :
int *p = &var;
NOTE : The datatype of the pointer variable should be the same as the
datatype of the variable whose address is been stored by the pointer. In the
above example it is ‘int’.
*p var
200 10
To print the value of ‘var’, we can do it by printing the ‘var’ variable directly or
using the dereference operator i.e. ‘*p’. ( output is 10 )
Pointer that points to another pointer is called as the double pointer or the
pointer to pointer.
E.g.
int *p = &var;
Arrays are the contiguous and equal blocks of memory which stores the values
of homogenous/specific datatype.
The above code creates 3 blocks of memory of 4 bytes each as the int datatype
holds up the values of 4 bytes. These blocks have contiguous memory
addresses, for e.g. 100, 104, 108. The arrays can be traversed by indexing and
the index of first block is 0.
NOTE : In the concept of arrays, the name of the array itself denotes the
memory address of the first block of the array. In the case of the above
example, “var” denotes the address of the first memory block of the array. If
we use “&var” to denote memory address then it will give an error.
We can get the pointer to the fist block of the array as follows :
int *p = var;
Here, p++ or p += 1 will increment the pointer to the memory address of the
next block in the array and p-- or p -= 1 will do the vice versa.
We can dereference the pointer (*p) to get the value stored at that address.
E.g.
struct emp
int ID;
string name;
};
Now, “struct emp” is a datatype which can be used to create multiple variables
as shown below :
struct emp{
int ID;
string name;
It is just like creating an object for a class. We can access the elements of the
structure using the dot(.) operator. For e.g. var1.ID and var1.name
You can shorten the name of your struct datatype created by using typedef
keyword which is used to replace the name of the datatype to another name.
E.g.
int ID;
string name;
} emp;
Now, we can use the datatype “emp” (shortened) to create variables as shown
below :
NOTE : The size of the structure is the sum of the sizes of the elements in it.
This is because each element/variable in the structure gets an amount of
memory size based upon its datatype. Each element has its separate memory.
Union is similar to struct but the difference in between both is that, the
elements in the union don’t have the separate memory. All the elements
shares the memory among themselves. The size of the union is equal to the
size of the largest element in it. The size of the largest element in the union is
shared by all the elements in it.
If we assign the value to an element in the Union, it utilizes the memory. Then
we can perform the operations on that particular element immediately after
the value is assigned to it. After that we can assign the value to next element
and perform operations over it, meanwhile the value assigned to the previous
element will be vanished as the memory is now utilized by the new element.
E.g.
union employee
int ID;
float sal;
};
cout<<emp.ID<<endl;
cout<<emp.sal<<endl;
Enum is a list of items where the items has sequential numbers assigned to it
starting from 0, 1, 2 … n. Therefore, the first item in enum stores 0, second
item stores 1 and so on. Now you can assign these items to any variable to
assign the number associated with them.
The list of items in the enum consist of a name and all the items are enclosed
between the curly brackets { item1, item2, item3 … itemN }.
E.g.
cout<<breakfast<<endl; // 0
cout<<lunch<<endl; // 1
cout<<dinner<<endl; // 2
Function Prototyping is used when you write the user-defined functions below
the main() function. Function prototyping should be done to avoid error in
such cases.
E.g.
int main()
return 0;
int sum(int a, int b) { return a+b; } //Here, a and b are formal parameters.
int diff(int a, int b) { return a-b; } //Here, a and b are formal parameters.
Call by Value and Call by Reference in C++
In call by value method, a copy of the original variable is been made and it is
passed to the function as the argument. On the other hand the function
receives the copy of the actual variable and treats it as its parameter.
return ++a; }
int main(){
cout<<increment(value)
return 0; }
*a = *a+1;
return 0; }
int main(){
cout<<value<<endl; // 10
increment(&value);
cout<<value<<endl; // 11
}
E.g. 2) Call by Reference ( Using the reference variable )
a = a+1;
return 0; }
int main(){
cout<<value<<endl; // 10
increment(value);
cout<<value<<endl; // 11
Inline functions are implemented by using the inline keyword. When we call
the function and pass some arguments, then the copy of the arguments is
passed to the function and the value is then processed and returned. It takes a
lot of time. So to reduce the time complexity we can use the inline function.
The inline function does everything( copying of arguments, passing and calling
function etc. ) at the compile time itself thus reducing the time complexity.
E.g.
return x*y;
int main() {
cout<<product(50,100)<<endl;
return 0; }
NOTE : Use the inline functions only when the functions implementation is
small and it is been called frequently throughout the program. If we make all
the functions inline or the large functions inline, then it will take up most of the
cache memory and the program size will increase, thus increasing the space
complexity.
E.g.
int main() {
message();
message(“Sweden”);
NOTE : The default argument should always be written at the last in the
parameters list of the function, i.e. at the right most side.
Function which calls itself repeatedly until the condition is met, then it is called
the Recursive Function.
if( num<=1 ){
return 1;
Consist of multiple functions with same name but different parameter list.
E.g.
return a+b;
return a+b+c;
int main(){
cout<<add(25,50)<<endl;
cout<<add(25,50,75)<<endl;
return 0; }
Object Oriented Programming in C++
Concepts in OOP’s :
Dynamic Binding = Code that executes is not known until the program runs.
Class Employee {
private:
int a,b,c;
public:
int d, e;
cout<<a<<endl<<b<<endl<<c<<endl<<d<<e;
};
a = a1;
b = b1;
c = c1;
int main() {
Employee obj;
obj.d = 40;
obj.e = 50;
obj.getData();
Access modifiers can be used with classes, class variables and methods. Default
access modifier is Public. Following are the accessibility of the class and its
elements with various access modifiers :
Access Modifiers Within the Class Sub Class Outside the Class
Public Yes Yes Yes
Private Yes No No
Protected Yes Yes No
Nesting of Member Functions in C++
E.g.
cout<<”Hello ”<<name<<endl;
void read(){
string name;
cin>>name;
Static members are common to all the objects. No separate copy of the static
members are made for separate objects. All the objects shares the same static
variables or methods. The static variables created in methods is by default
initialized to zero(0). The static method in the class can access only the static
variables or other static methods in the class and such static method can be
executed using the name of the class not even creating the object of the class.
Array of objects in C++
If there is a need to create multiple number of objects for a class then we can
use the array of objects to create multiple objects using a single name. Array of
objects is same as creating array of any other datatype like integer or float.
int main() {
return 0;
class complex
{
int a, b;
public:
void setData(int v1, int v2)
{
a = v1;
b = v2;
}
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 function is the function with any return type. The friend function can
access the private members of the class and it lies outside the class. However,
we need to declare the friend function inside the class but the implementation
is written outside the class. The friend function is not the member of the class,
it is a separate function outside the class but it has permission to access the
data of the class weather it may be of any access specifier.
class complex
{
int a, b;
public:
friend complex sumComplex(complex o1, complex o2);
void showNumber()
{
cout<<"Your number is : "<<a<<" + i"<<b<<endl;
}
};
int main()
{
complex ob1, ob2, sum;
ob1.setNumber(4,8);
ob2.setNumber(5,9);
ob1.showNumber();
ob2.showNumber();
sum = sumComplex(ob1,ob2);
sum.showNumber();
return 0;
}
If we want to access the data of one class into another class then we can use
the friend classes concept in C++. As we make the friend function by declaring
it inside the class, similarly we declare another class as friends in the original
class.
class complex
{
int a,b;
public:
// friend complex Calculator :: add(complex o1, complex o2); //Making
friends with an individual method/Member friend function.
friend class Calculator; // This is Friend class.
void showNumber()
{
cout<<"Your number is : "<<a<<" + i"<<b<<endl;
}
};
int main()
{
complex obj1, obj2, result;
Calculator obj;
obj1.setNumber(4,8);
obj2.setNumber(6,4);
obj1.showNumber();
obj2.showNumber();
result = obj.add(obj1,obj2);
result.showNumber();
return 0;
}
Constructors in C++
Constructor is the special member function which has the same name as the
class name. It is automatically invoked when the object of the class is created.
Constructors are generally used to initialize the private variables of the class.
The code inside the constructor is executed once the object of that class is
created. The Constructor has no return type and should be declared in the
public section of the class.
E.g.
#include<iostream>
using namespace std;
class Sum
{
int a,b;
public:
void ShowSum()
{
cout<<"\nThe Addition of Two Numbers is : "<<a+b<<endl;
}
};
int main()
{
Sum obj(10,20);
obj.ShowSum();
return 0;
}
Parameterized and Default Constructors In C++
E.g.
#include <iostream>
using namespace std;
class complex
{
int a, b;
public:
complex(int, int);
void display()
{
cout << "Complex Number is : " << a << " + i" << b << endl;
}
};
int main()
{
complex a(10, 12); // Implicit Call
complex b = complex(15, 45); // Explicit Call
a.display();
b.display();
return 0;
}
If the constructor of the class is not written and implemented by the user then
the default constructor is executed on creation of the object.
Contructor Overloading in C++
E.g.
#include<iostream>
using namespace std;
class area
{
public:
area(float side)
{
cout<<"Area of Square is : "<<(side*side)<<endl;
}
area(float base, float height)
{
cout<<"Area of Triangle is : "<<(0.5*(base*height))<<endl;
}
};
int main()
{
area square(10.5); //Implicit Call
area triangle = area(5,10); //Explicit Call
return 0;
}
It is same as the functions with default arguments. The default arguments has
an value assigned to them, if the value to the argument is provided by the user
then that value is used, but if the value is not provided explicitly by the user
then the default value is been used.
E.g.
#include<iostream>
using namespace std;
class Info
{
string name, country;
public:
void display()
{
cout<<"Hello, My name is "<<name<<" and I am from
"<<country<<"."<<endl;
}
};
int main()
{
string name,country;
obj1.display();
obj2.display();
return 0;
}
class Emp
{
public:
Emp() {}
int main()
{
string name;
int id;
float salary;
return 0;
}
Copy Constructor in C++
Copy Constructor is used to use the copy of the object of a class. We pass the
reference/copy of the object as an argument to the constructor. We can create
a new object using the data of the argument object.
NOTE : Compiler can create maximum of 2 constructors on its own. First one is
the default constructor and second is the copy constructor. If we create our
own constructor in the class then the compiler creates only a copy constructor
if not created. If no constructor is created at all, then compiler creates a
default constructor.
E.g.
#include <iostream>
using namespace std;
class Copy
{
int a;
public:
Copy() { a = 0; } // Default Constructor
Copy(int value)
{
a = value;
}
/*
Copy(Copy &obj) // Copy Constructor
{
cout << "\nCopy Constructor Called!" << endl;
a = obj.a;
}
*/
void show()
{
cout << "Value is : " << a << endl;
}
};
int main()
{
Copy obj1(10), obj2, obj3, obj4;
obj1.show();
obj2.show();
return 0;
}
Destructors in C++
Destructor is written as same as the constructor i.e. it has the same name as of
the class with a tilde( ~ ) sign in front of it. Destructor never takes any
argument nor does it returns any value.
E.g.
#include <iostream>
using namespace std;
int count = 0;
class Num
{
public:
Num()
{
count += 1;
cout << "\nConstructor for object number " << count << endl;
}
~Num()
{
cout << "\nDestructor for object number " << count << endl;
count -= 1;
}
};
int main()
{
cout << "\nMain Function Start!\n";
Num n1;
{
cout << "\nEntering Block\n";
Num n2, n3;
cout << "\nExiting Block\n";
}
cout << "\nMain Function End!\n";
return 0;
}
Inheritance in C++
Single Inheritance
Multiple Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Inheritance Syntax and Visibility Mode in C++
Body of Class….
};
NOTE : The private members of the base class can never be inherited in the
derived class.
There are three visibility modes in C++ Public, Private & Protected
Public = It means that the derived class can access the public and protected
members of the base class, but not the private members of the base class. The
protected members of the base class remains protected members in the
derived class and public members of the base class remains public in the
derived class.
Private = It means that the derived class can privately access the public and
protected members of the base class, but cannot access the private members
of the base class. The public and protected members of the base class becomes
private in the derived class.
Protected = It means that the derived class can access the public and protected
members of the base class protectively, but cannot access the private
members of the base class. The public and protected members in the base
class becomes protected in the derived class.
Body of Class….
};
We need to resolve the ambiguity by using the scope resolution operator for
calling a particular method from a particular class.
E.g.
#include<iostream>
using namespace std;
class Base1
{
public:
void greet()
{
cout<<"\nHello, How are you?"<<endl;
}
};
class Base2
{
public:
void greet()
{
cout<<"\nHi, What's up?"<<endl;
}
};
int main()
{
Derived obj;
obj.greet();
return 0;
}
NOTE : When there are methods with same name and signature in the base
class and derived class in the case of single inheritance, then there also occurs
an ambiguity. But in such cases the ambiguity is resolved automatically,
wherein the method written in the derived class is executed when called rather
than executing the method inherited from the base class.
Virtual Base Class solves the problem. We can make those derived classes as
virtual base classes. So whenever those derived classes are inherited further by
a class then only a single copy of that member will be allowed to be inherited,
thus eradicating the problem.
Syntax of Virtual Base Class :
Class Body….
};
E.g.
#include <iostream>
using namespace std;
class Student
{
protected:
int rollno;
public:
void SetRoll(int roll)
{
rollno = roll;
}
void Display()
{
cout << "\nRoll Number : " << rollno << endl;
}
};
public:
void SetTestMarks(int m, int s, int l)
{
Maths = m;
Science = s;
Language = l;
}
void ShowTestMarks()
{
cout << "\nMarks in Maths : " << Maths << endl
<< "Marks in Science : " << Science << endl
<< "Marks in Language : " << Language << endl;
}
};
public:
void SetSportsMarks(int m, int a, int g)
{
medical = m;
athletics = a;
game = g;
}
void ShowSportsMarks()
{
cout << "\nMarks in Medical : " << medical << endl
<< "Marks in Athletics : " << athletics << endl
<< "Marks in Game : " << game << endl;
}
};
public:
void CalculateResult()
{
testpercent = (Maths + Science + Language) / 3;
sportspercent = (medical + athletics + game) / 3;
totalpercent = (testpercent + sportspercent) / 2;
}
void ShowResult()
{
cout << "\nTest Percentage : " << testpercent << "%" << endl
<< "Sports Percentage : " << sportspercent << "%" << endl
<< "Total Percentage : " << totalpercent << "%" << endl;
int main()
{
Result obj;
int roll;
int tmarks[3];
int smarks[3];
obj.SetRoll(roll);
obj.SetTestMarks(tmarks[0], tmarks[1], tmarks[2]);
obj.SetSportsMarks(smarks[0], smarks[1], smarks[2]);
obj.CalculateResult();
obj.Display();
obj.ShowTestMarks();
obj.ShowSportsMarks();
obj.ShowResult();
return 0;
}
In Multiple inheritance, base classes are constructed in the order in which they
appear in the class declaration. In Multilevel inheritance, the constructors are
executed in the order of inheritance.
The constructors for virtual base classes are invoked before an non virtual base
class. If there are multiple virtual base classes, they are invoked in the order
declared. Any non-virtual base class are then constructed before the derived
class constructor is executed.
Syntax : Base1 has variable ‘x’, Base2 has ‘y’ and Derived has ‘z’.
y = arg3;
Base1(arg1);
Base2(arg2);
y = arg3;
E.g.
#include <iostream>
using namespace std;
/*
Case 1:
class B: public A{
//Order of Execution of Constructors --> First A() then B();
}
Case 2:
class C: public A, public B{
//Order of Execution of Constructors --> First A(), then B() and
then C();
}
Case 3:
class A: public B, virtual public C{
//Order of Execution of Constructors --> First C(), then B() and
then A();
}
*/
class Base1
{
int data1;
public:
Base1(int i)
{
data1 = i;
cout << "\nBase1 class constructor called!" << endl;
}
void printdata1()
{
cout << "\nThe value of data1 is : " << data1 << endl;
}
};
class Base2
{
int data2;
public:
Base2(int i)
{
data2 = i;
cout << "\nBase2 class constructor called!" << endl;
}
void printdata2()
{
cout << "\nThe value of data2 is : " << data2 << endl;
}
};
public:
Derived(int a, int b, int c, int d) : Base1(a), Base2(b)
{
derived1 = c;
derived2 = d;
cout << "\nDerived Class constructor called!" << endl;
}
void printdata()
{
cout << "\nThe value of derived1 = " << derived1 << " derived2 = " <<
derived2 << endl;
}
};
int main()
{
Derived obj(10, 20, 30, 40);
obj.printdata1();
obj.printdata2();
obj.printdata();
return 0;
}
}
Initialization Section is used to initialize the variables in the class. We write the
variables as a function and then pass the argument with which it is to be
initialized.
E.g.
class Test
public:
cout<<”\nInside Constructor!”<<endl;
};
Pointers stores the address of the variables. We can use the “new” and
“delete” keyword in respect to the pointers for the purpose of dynamic
memory allocation.
The “new” keyword is used to allocate memory dynamically for the values of
different datatypes. It is similar to “malloc” and “calloc” in C language.
Syntax:
Syntax:
E.g.
#include <iostream>
using namespace std;
int main()
{
int *var1 = new int(25);
float *var2 = new float();
string *var3 = new string();
*var2 = 85.52;
*var3 = "Pointer";
The pointer can also be assigned to the objects of the classes. We can use the
variables and methods in the classes by dereferencing the pointer
( (*ptr).method() ). Using the “new” operator we can create the objects
dynamically at the run time and using the “delete” operator we can free the
memory of the object or destroy the object.
We dereference the pointer using the Dereference operator (*). Another way
of dereferencing the pointer is using the Arrow operator (->). The Arrow
operator allows us to dereference the pointer and use the variables and
methods inside the object.
Syntax :
ptr->method();
ptr->variable;
(*ptr).method();
(*ptr).variable;
E.g.
#include <iostream>
using namespace std;
class Complex
{
int real, imaginary;
public:
Complex(int r, int i)
{
real = r;
imaginary = i;
}
void display()
{
cout << "\nReal Part is : " << real << endl;
cout << "Imaginary Part is : " << imaginary << "i" << endl;
}
};
int main()
{
Complex obj(10, 20);
Complex *ptr = &obj;
(*ptr).display();
We can create the array of objects in case multiple objects are needed of a
particular class. We can create the array of objects without pointer (at compile
time) or with pointer (at run time). However, while creating the array of object
the only thing is that the respective class should only have a simple
constructor, and no parameterized constructor. You can create methods for
taking parameters instead of creating a parameterized constructor. Therefore,
array of objects can be created of only those classes which has only simple
constructors and no parameterized constructors.
E.g.
#include <iostream>
using namespace std;
class Test
{
int a, b;
public:
void setData(int x, int y)
{
a = x;
b = y;
}
void printData()
{
cout << "\nValues are : " << a << " " << b << endl;
}
};
int main()
{
Test obj[3]; // Array of objects at compile time.
obj[0].setData(10, 20);
obj[0].printData();
obj[1].setData(20, 20);
obj[1].printData();
obj[2].setData(30, 20);
obj[2].printData();
ptr->setData(20, 10);
ptr->printData();
ptr += 1;
ptr->setData(20, 20);
ptr->printData();
ptr += 1;
ptr->setData(20, 30);
ptr->printData();
return 0;
}
“This” is a keyword which is a pointer which points to the object of the class. It
has two use cases:
Syntax:
this->var = var;
Syntax:
Body….
return *this;
E.g.
#include <iostream>
using namespace std;
class Test
{
int data;
public:
Test &setData(int data)
{
this->data = data;
return *this;
}
void showData()
{
cout << "\nThe data value is : " << data << endl;
}
};
int main()
{
Test obj;
Polymorphism in C++
Polymorphism is made up from two words -> Poly (Many) & Morphs (Forms).
The polymorphism that takes place at run time. It is called as dynamic binding
or late binding. There are two types under it.
A pointer of the Base class can be assigned to the object of the derived class.
Therefore the Base Class pointer can point towards the object of the derived
class. This is called as late binding. The derived class has inherited the Base
class with some visibility mode, and so it contains several methods and
variables of the base class in it. Therefore being the base class pointer, it can
only access the inherited members of the base class in the derived class.
E.g.
#include <iostream>
using namespace std;
class Base
{
public:
int base_var;
void display()
{
cout << "\nThe Value of Base Variable = " << base_var << endl;
}
};
void display()
{
cout << "\nThe Value of Derived Variable = " << derived_var << endl;
}
};
int main()
{
Base *base_pointer = new Derived;
Derived *derived_pointer = new Derived;
base_pointer->display();
derived_pointer->display(); //Function Overriding;
return 0;
}
Virtual Functions in C++
We know that, if we create a Base class pointer and assign it to the object of
the derived class then the pointer can only access the members of the base
class which are inherited in the derived class. But it is opposite in the case of
Virtual Function. We can make any function “virtual” in the base class. Now the
base class pointer assigned to the object of the derived class cannot access the
virtual function of the base class inherited in the derived class and it instead
runs/executes the function with the same name of the derived class. It is a
type of run time polymorphism.
E.g.
#include <iostream>
using namespace std;
class Base
{
public:
int base_var = 90;
void display()
{
cout << "\nThe Value of Derived Variable = " << derived_var << endl;
}
};
int main()
{
Base *base_pointer = new Derived;
Base *new_base_pointer = new Base;
Derived *derived_pointer = new Derived;
new_base_pointer->display();
base_pointer->display();
derived_pointer->display(); // Function Overriding;
return 0;
}
The base class which is created for the purpose of inheritance ( to add up to its
variables and functions in the derived class ) is called as the Abstract base class.
The abstract base class contains at least one pure virtual function in it. The
pure virtual function is a virtual function which is declared in the base class and
it is initialized to zero (Do Nothing Function). Now it becomes
mandatory/compulsory to overwrite this function in the derived class and give
its implementation so that when called it can be executed. This mechanism of
abstracting/hiding the function of the base class and then re-declaring it in the
derived class is called as Abstraction.
E.g.
#include <iostream>
using namespace std;
public:
Actor(int films, int awards, float networth, bool married)
{
Films = films;
Awards = awards;
Networth = networth;
Married = married;
}
public:
SRK(int age, int films, int awards, float networth, bool married) :
Actor(films, awards, networth, married)
{
this->age = age;
}
void display()
{
cout << "\n"
<< Name << " is a " << age << " years old Actor and he had done
over " << Films << " films and won " << Awards << " awards. He is known as \""
<< Tag << "\" and his networth is around $" << Networth << " million.";
if (Married)
cout << " He is a married person." << endl;
else
cout << " He is not married and he's happy." << endl;
}
};
public:
SLK(int age, int films, int awards, float networth, bool married) :
Actor(films, awards, networth, married)
{
this->age = age;
}
void display()
{
cout << "\n"
<< Name << " is a " << age << " years old Actor and he had done
over " << Films << " films and won " << Awards << " awards. He is known as \""
<< Tag << "\" and his networth is around $" << Networth << " million.";
if (Married)
cout << " He is a married person." << endl;
else
cout << " He is not married and he's happy." << endl;
}
};
int main()
{
SRK srk(52, 125, 75, 655.75, true);
SLK slk(54, 115, 65, 545.35, false);
Actor *ptr[2];
ptr[0] = &srk;
ptr[1] = &slk;
ptr[0]->display();
ptr[1]->display();
return 0;
}
Files are the storage area for the data of various kinds. The files can be of
different types like text files, image files, audio files etc. In the file each
character or block is equivalent to some ASCII value or UNICODE value which is
then converted to the binary and therefore the file is stored on to the disk in
the format of binary.
To read and write into the files we need to include the header file “fstream”
i.e. file stream. The useful classes for working with files in cpp are:
In order to work with files we need to open the file. Primarily there are two
ways to open the file:
Syntax:
Syntax:
After performing the desired operations on the opened file, the file must be
closed in order to release or free up its all the resources. We use the close
method to close the opened file.
Syntax:
File_Object.close();
End of File -
The “eof()” defines the end of file. It can used with the while loop to read all
the content of the file.
NOTE: For the purpose of reading a complete line from the file we use the
getline() function. This function is present in the “string” header file and so we
need to include “string” for using the function.
int main()
{
ofstream fout("FileProgram.txt"); //fout is now an output file stream
just similar to cout.
string str;
cout<<"\nEnter Your Name : ";
cin>>str;
fout<<str<<" is my name!";
fout.close();
return 0;
}
int main()
{
ofstream fout;
fout.open("FileProgram.txt");
string str;
cout << "\nEnter Your Name : ";
cin >> str;
fout << "This is " << str << " and this is my second file program";
fout.close();
ifstream fin;
fin.open("FileProgram.txt");
while (fin.eof() == 0)
{
getline(fin, str);
cout << "\nThe Content of File is : " << str;
}
fin.close();
return 0;
}
Templates in C++
Class is a blue-print or a structure for the objects. Similarly we can say that
templates are the blue-print or structure for the classes. We can create a
template and then use it for different datatypes as required. Templates are
also called as the parameterized classes. We provide datatype as a parameter
to the template.
We prefer the use of template to follow the “DRY” principle i.e. “Don’t Repeat
Yourself” principle. Templates allows us to do Generic Programing (Generic
Templates can be used for various datatypes ).
Syntax for creating Template : ‘T’ is the Datatype that we pass as parameter.
class class_name {
};
int main() {
}
E.g. Dot Product of Vectors
#include <iostream>
using namespace std;
T dotProduct(Vector &v)
{
T sum = 0;
return sum;
}
};
int main()
{
Vector<float> v1;
v1.arr[0] = 4.2;
v1.arr[1] = 2.9;
v1.arr[2] = 3.7;
Vector<float> v2;
v2.arr[0] = 1.0;
v2.arr[1] = 2.54;
v2.arr[2] = 3.213;
return 0;
}
class class_name {
};
int main() {
E.g.
#include <iostream>
using namespace std;
public:
addition(T1 data1, T2 data2)
{
this->data1 = data1;
this->data2 = data2;
}
void result()
{
cout << "\nResult = " << data1 + data2;
}
};
int main()
{
addition<int, float> obj(45, 457.56);
obj.result();
return 0;
}
Templates with Default Parameters in C++
We can write templates with default parameters, i.e. we can provide the
default datatypes to the template parameter. If no datatypes are specified at
the time of creating the object of the class then those default parameter
datatypes are been used.
Syntax:
class class_name {
};
int main() {
E.g.
#include <iostream>
using namespace std;
int main()
{
addition obj1(45.98, 78.24);
addition<int, float> obj2(85, 54.45);
addition<int, int> obj3(95, 108);
return 0; }
Function Template and Function Template with Parameters in C++
Syntax:
Body of Function…;
E.g.
#include <iostream>
float avg(T1 a, T2 b)
{
float result = (a + b) / 2.0;
return result;
}
int main()
{
int a = 19, b = 24;
return 0;
}
Member Function Templates & Overloading Template Functions in C++
Member function templates are useful when we write the member function of
the class outside the class. We need to write the template for the function and
declare it outside the class and then write its implementation.
E.g.
#include <iostream>
class Test
{
T data;
public:
Test(T value)
{
data = value;
}
void display();
};
void Test<T>::display()
{
cout << "\nThe Data value is = " << data;
}
int main()
{
Test<int> o1(42);
Test<char> o2('S');
Test<float> o3(93.65);
o1.display();
o2.display();
o3.display();
return 0;
}
We can also overload the template functions. The function with exact match of
the datatype when called has the first preference.
E.g.
#include <iostream>
using namespace std;
int main()
{
add(45, 85); //Exact match so the first function is called.
add(78.5, 95.25);
return 0;
}
Containers are objects that stores data & uses template classes (e.g. Vector )
Algorithms are procedures that processes data & it uses template functions
(e.g. Sorting, Searching, Merging etc. )
Sequence Containers :
Derived Containers : The speed of the operations depends on the used data
structure as per our requirement.
Vector is similar to array. Size of the vector can be dynamically changed as per
required but it is not possible in the case of array. There are several methods
and variables with respect to the vector. Refer the “methods of vector”
document on “cplusplus.com” for such methods and variables.
Syntax:
OR
OR
OR
E.g.1.
#include <iostream>
#include <vector>
int main()
{
vector<int> vec1;
int value, size;
vec1.insert(iter, 25);
display(vec1);
return 0;
}
E.g.2.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<char> vec1(4); // 4 Element Character Vector;
vector<char> vec2(vec1); // Vector vec2 has the size of vec1;
vector<int> vec3(6, 5); // Adds value 5 in the vector for 6 times.
vec1.push_back('S');
display(vec1);
vec2.push_back('P');
vec2.push_back('N');
vec2.push_back('H');
vec2.push_back('S');
display(vec2);
display(vec3);
return 0;
}
List is also a container and is used to store data in it. It is bidirectional linear list
which provides efficient insertion, deletion and many more operations. It is
different from an array. Array stores elements with contiguous memory
allocation whereas list is the STL implementation of “Linked List” data structure
where the elements are not stored in contiguous blocks of memory. In STL
there are several methods and variables which can be used in respect to List.
Refer “cppreference.com” for such methods and varaibles.
Syntax:
OR
E.g.
#include <iostream>
#include <list>
int main()
{
list<int> list1;
list<int> list2(2);
list1.push_back(42);
list1.push_back(20);
list1.push_front(25);
list1.push_back(43);
list1.push_front(95);
list<int>::iterator iter;
iter = list2.begin();
*iter = 40;
++iter;
*iter = 45;
display(list1);
display(list2);
list1.pop_back();
list1.remove(25);
list1.pop_front();
list1.sort();
list1.reverse();
list1.merge(list2);
display(list1);
return 0;
}
E.g.
#include <iostream>
#include <map>
#include <string>
int main()
{
map<string, int> marks;
marks["Suraj"] = 42;
marks["Piyush"] = 40;
marks["Tanmay"] = 53;
marks["Aditya"] = 24;
return 0;
}
E.g.
#include <iostream>
#include <functional>
#include <algorithm>
using namespace std;
int main()
{
int arr[] = {45, 98, 30, 14, 75, 21};
return 0;
}