C++ Part2
C++ Part2
Like other programming languages, array in C++ is a group of similar types of elements that have
contiguous memory location.
In C++ std::array is a container that encapsulates fixed size arrays. In C++, array index starts from
0. We can store only fixed set of elements in C++ array.
#include <iostream>
using namespace std;
int main()
{
int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
//traversing array
for (int i = 0; i < 5; i++)
{
cout<<arr[i]<<"\n";
}
}
#include <iostream>
using namespace std;
int main()
{
int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
//traversing array
for (int i: arr)
{
cout<<i<<"\n";
}
}
functionname(arrayname); //passing array to function
#include <iostream>
using namespace std;
void printArray(int arr[5]);
int main()
{
int arr1[5] = { 10, 20, 30, 40, 50 };
int arr2[5] = { 5, 15, 25, 35, 45 };
printArray(arr1); //passing array to function
printArray(arr2);
}
void printArray(int arr[5])
{
cout << "Printing array elements:"<< endl;
for (int i = 0; i < 5; i++)
{
cout<<arr[i]<<"\n";
}
}
#include <iostream>
using namespace std;
int main()
{
int test[3][3]; //declaration of 2D array
test[0][0]=5; //initialization
test[0][1]=10;
test[1][1]=15;
test[1][2]=20;
test[2][0]=30;
test[2][2]=10;
//traversal
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 3; ++j)
{
cout<< test[i][j]<<" ";
}
cout<<"\n"; //new line at each row
}
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int test[3][3] =
{
{2, 5, 5},
{4, 0, 3},
{9, 1, 8} }; //declaration and initialization
//traversal
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 3; ++j)
{
cout<< test[i][j]<<" ";
}
cout<<"\n"; //new line at each row
}
return 0;
}
C++ Pointers
The pointer in C++ language is a variable, it is also known as locator or indicator that points to an
address of a value.
Advantage of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees
etc. and used with arrays, structures and functions.
3) It makes you able to access any memory location in the computer's memory.
Usage of pointer
In c language, we can dynamically allocate memory using malloc() and calloc() functions where
pointer is used.
Pointers in c language are widely used in arrays, functions and structures. It reduces the code and
improves the performance.
Symbols used in pointer
Symbol Name Description
Declaring a pointer
The pointer in C++ language can be declared using ∗ (asterisk symbol).
int ∗ a; //pointer to int
char ∗ c; //pointer to char
Pointer Example
Example of using pointers printing the address and value.
#include <iostream>
using namespace std;
int main()
{
int number=30;
int ∗ p;
p=&number;//stores the address of number variable
cout<<"Address of number variable is:"<<&number<<endl;
cout<<"Address of p variable is:"<<p<<endl;
cout<<"Value of p variable is:"<<*p<<endl;
return 0;
}
The size, which is calculated by the sizeof() operator, is the amount of RAM occupied in the
computer.
sizeof(data_type);
In the above syntax, the data_type can be the data type of the data, variables, constants, unions,
structures, or any other user-defined data type.
example.
#include <iostream>
using namespace std;
int main()
{
// Determining the space in bytes occupied by each data type.
std::cout << "Size of integer data type : " <<sizeof(int)<< std::endl;
std::cout << "Size of float data type : " <<sizeof(float)<< std::endl;
std::cout << "Size of double data type : " <<sizeof(double)<< std::endl;
std::cout << "Size of char data type : " <<sizeof(char)<< std::endl;
return 0;
}
#include <iostream>
using namespace std;
class Base
{
int a;
};
int main()
{
Base b;
std::cout << "Size of class base is : "<<sizeof(b) << std::endl;
return 0;
}
If we add one more integer variable in a class, then the code would look like:
#include <iostream>
using namespace std;
class Base
{
int a;
int d;
};
int main()
{
Base b;
std::cout << "Size of class base is : "<<sizeof(b) << std::endl;
return 0;
}
if we add a char variable in the above code, then the code would look like:
#include <iostream>
using namespace std;
class Base
{
int a;
int d;
char ch;
};
int main()
{
Base b;
std::cout << "Size of class base is : "<<sizeof(b) << std::endl;
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int arr[]={10,20,30,40,50};
std::cout << "Size of the array 'arr' is : "<<sizeof(arr) << std::endl;
return 0;
}
o When an operand is of pointer type.
#include <iostream>
using namespace std;
int main()
{
int *ptr1=new int(10);
std::cout << "size of ptr1 : " <<sizeof(ptr1)<< std::endl;
std::cout << "size of *ptr1 : " <<sizeof(*ptr1)<< std::endl;
char *ptr2=new char('a');
std::cout <<"size of ptr2 : " <<sizeof(ptr2)<< std::endl;
std::cout <<"size of *ptr2 : "<<sizeof(*ptr2)<< std::endl;
double *ptr3=new double(12.78);
std::cout <<"size of ptr3 : " <<sizeof(ptr3)<< std::endl;
std::cout <<"size of *ptr3 : "<<sizeof(*ptr3)<< std::endl;
return 0;
}
Example:
#include <iostream>
using namespace std;
int main()
{
int *ptr; // integer pointer declaration
int marks[10]; // marks array declaration
std::cout << "Enter the elements of an array :" << std::endl;
for(int i=0;i<10;i++)
{
cin>>marks[i];
}
ptr=marks; // both marks and ptr pointing to the same element..
std::cout << "The value of *ptr is :" <<*ptr<< std::endl;
std::cout << "The value of *marks is :" <<*marks<<std::endl;
}
Another example.
#include <iostream>
using namespace std;
int main()
{
int ptr1[5]; // integer array declaration
int *ptr2[5]; // integer array of pointer declaration
std::cout << "Enter five numbers :" << std::endl;
for(int i=0;i<5;i++)
{
std::cin >> ptr1[i];
}
for(int i=0;i<5;i++)
{
ptr2[i]=&ptr1[i];
}
// printing the values of ptr1 array
std::cout << "The values are" << std::endl;
for(int i=0;i<5;i++)
{
std::cout << *ptr2[i] << std::endl;
}
}
In C++, we cannot assign the address of a variable to the variable of a different data type.
Consider the following example:
int *ptr; // integer pointer declaration
float a=10.2; // floating variable initialization
ptr= &a; // This statement throws an error.
In the above example, we declare a pointer of type integer, i.e., ptr and a float variable, i.e., 'a'.
After declaration, we try to store the address of 'a' variable in 'ptr', but this is not possible in C++
as the variable cannot hold the address of different data types.
#include <iostream.h>
using namespace std;
int main()
{
int *ptr;
float f=10.3;
ptr = &f; // error
std::cout << "The value of *ptr is : " <<*ptr<< std::endl;
return 0;
}
In the above program, we declare a pointer of integer type and variable of float type. An integer
pointer variable cannot point to the float variable, but it can point to an only integer variable.
C++ has overcome the above problem by using the C++ void pointer as a void pointer can hold
the address of any data type.
#include <iostream>
using namespace std;
int main()
{
void *ptr; // void pointer declaration
int a=9; // integer variable initialization
ptr=&a; // storing the address of 'a' variable in a void pointer variable.
std::cout << &a << std::endl;
std::cout << ptr << std::endl;
return 0;
}
They are mainly useful for event-driven applications, callbacks, and even for storing the functions
in arrays.
All the functions and machine code instructions are data. This data is a bunch of bytes, and all
these bytes have some address in RAM. The function pointer contains RAM address of the first
instruction of a function.
int (*FuncPtr) (int,int);
The above syntax is the function declaration. As functions are not simple as variables, but C++ is a
type safe, so function pointers have return type and parameter list. In the above syntax, we first
supply the return type, and then the name of the pointer, i.e., FuncPtr which is surrounded by the
brackets and preceded by the pointer symbol, i.e., (*). After this, we have supplied the parameter
list (int,int). The above function pointer can point to any function which takes two integer
parameters and returns integer type value.
Address of a function
We can get the address of a function very easily. We just need to mention the name of the
function, we do not need to call the function.
Example.
#include <iostream>
using namespace std;
int main()
{
std::cout << "Address of a main() function is : " <<&main<< std::endl;
return 0;
}
In the above program, we are displaying the address of a main() function. To print the address of
a main() function, we have just mentioned the name of the function, there is no bracket not
parameters. Therefore, the name of the function by itself without any brackets or parameters
means the address of a function.
We can use the alternate way to print the address of a function, i.e., &main.
#include <iostream>
using namespace std;
int add(int a , int b)
{
return a+b;
}
int main()
{
int (*funcptr)(int,int); // function pointer declaration
funcptr=add; // funcptr is pointing to the add function
int sum=funcptr(5,5);
std::cout << "value of sum is :" <<sum<< std::endl;
return 0;
}
#include <iostream>
using namespace std;
void printname(char *name)
{
std::cout << "Name is :" <<name<< std::endl;
}
int main()
{
char s[20]; // array declaration
void (*ptr)(char*); // function pointer declaration
ptr=printname; // storing the address of printname in ptr.
std::cout << "Enter the name of the person: " << std::endl;
cin>>s;
cout<<s;
ptr(s); // calling printname() function
return 0;
}
New operator
A new operator is used to create the object while a delete operator is used to delete the object.
When the object is created by using the new operator, then the object will exist until we explicitly
use the delete operator to delete the object. Therefore, we can say that the lifetime of the object
is not related to the block structure of the program.
Syntax
pointer_variable = new data-type
The above syntax is used to create the object using the new operator. In the above
syntax, 'pointer_variable' is the name of the pointer variable, 'new' is the operator, and 'data-
type' defines the type of the data.
Example 1:
int *p;
p = new int;
Example 2:
1. float *q;
2. q = new float;
In the above case, the declaration of pointers and their assignments are done separately. We can
also combine these two statements as follows:
1. int *p = new int;
2. float *q = new float;
1. *p = 45;
2. *q = 9.8;
We assign 45 to the newly created int object and 9.8 to the newly created float object.
o We can also assign the values by using new operator which can be done as follows:
pointer_variable = new data-type(value);
Examples.
1. int *p = new int(45);
2. float *p = new float(9.8);
pointer-variable = new data-type[size];
Example:
int *a1 = new int[8];
In the above statement, we have created an array of type int having a size equal to 8 where p[0] refers first element, p[1] refers the first
element, and so on.
Delete operator
When memory is no longer required, then it needs to be deallocated so that the memory can be
used for another purpose. This can be achieved by using the delete operator, as shown below:
delete pointer_variable;
In the above statement, 'delete' is the operator used to delete the existing object,
and 'pointer_variable' is the name of the pointer variable.
In the previous case, we have created two pointers 'p' and 'q' by using the new operator, and can
be deleted by using the following statements:
1. delete p;
2. delete q;
The dynamically allocated array can also be removed from the memory space by using the
following syntax:
delete [size] pointer_variable;
In the above statement, we need to specify the size that defines the number of elements that are
required to be freed. The drawback of this syntax is that we need to remember the size of the
array. But, in recent versions of C++, we do not need to mention the size as follows:
delete [ ] pointer_variable;
Example:
#include <iostream>
using namespace std
int main()
{
int size; // variable declaration
int *arr = new int[size]; // creating an array
cout<<"Enter the size of the array : ";
std::cin >> size; //
cout<<"\nEnter the element : ";
for(int i=0;i<size;i++) // for loop
{
cin>>arr[i];
}
cout<<"\nThe elements that you have entered are :";
for(int i=0;i<size;i++) // for loop
{
cout<<arr[i]<<",";
}
delete arr; // deleting an existing array.
return 0;
}
o It does not use the sizeof() operator as it automatically computes the size of the data object.
o It automatically returns the correct data type pointer, so it does not need to use the
typecasting.
o Like other operators, the new and delete operator can also be overloaded.
o It also allows you to initialize the data object while creating the memory space for the
object.
C++ OOPs Concepts
The major purpose of C++ programming is to introduce the concept of object orientation to the
C programming language.
Object Oriented Programming is a paradigm that provides many concepts such as inheritance,
data binding, polymorphism etc.
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
Class
Collection of objects is called class. It is a logical entity.
Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example: to
convince the customer differently, to draw something e.g. shape or rectangle etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example: phone
call, we don't know the internal processing.
C++ Object
In C++, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc.
In other words, object is an entity that has state and behavior. Here, state means data and
behavior means functionality.
Object is an instance of a class. All the members of the class can be accessed through object.
C++ Class
In C++, class is a group of similar objects. It is a template from which objects are created. It can
have fields, methods, constructors etc.
class Student
{
public:
int id; //field or data member
float salary; //field or data member
String name;//field or data member
}
C++ Object and Class Example
Let's see an example of class that has two fields: id and name. It creates instance of the class,
initializes the object and prints the object value.
#include <iostream>
using namespace std;
class Student {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
};
int main() {
Student s1; //creating an object of Student
s1.id = 201;
s1.name = "Sonoo Jaiswal";
cout<<s1.id<<endl;
cout<<s1.name<<endl;
return 0;
}
Example of C++ class where we are initializing and displaying object through method.
#include <iostream>
using namespace std;
class Student {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
void insert(int i, string n)
{
id = i;
name = n;
}
void display()
{
cout<<id<<" "<<name<<endl;
}
};
int main(void) {
Student s1; //creating an object of Student
Student s2; //creating an object of Student
s1.insert(201, "Sonoo");
s2.insert(202, "Nakul");
s1.display();
s2.display();
return 0;
}
Example of C++ class where we are storing and displaying employee information
using method.
#include <iostream>
using namespace std;
class Employee {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
void insert(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
e1.insert(201, "Sonoo",990000);
e2.insert(202, "Nakul", 29000);
e1.display();
e2.display();
return 0;
}
o Public: When the member is declared as public, it is accessible to all the functions of the
program.
o Private: When the member is declared as private, it is accessible within the class only.
o Protected: When the member is declared as protected, it is accessible within its own class as
well as the class immediately derived from it.
Visibility of Inherited Members
Base class visibility Derived class visibility
Scope resolution operator (::) in C++ is used to define a function outside a class or
when we want to use a global variable but also has a local variable with the same
name.
using namespace std;
char c = 'a'; // global variable (accessible to all functions)
int main() {
char c = 'b'; // local variable (accessible only in main function)
cout << "Local variable: " << c << "\n";
cout << "Global variable: " << ::c << "\n"; // Using scope resolution operator
return 0;
}
class Game {
public:
void play(); // Function declaration
};
int main() {
Game g;
g.play();
return 0;
}
C++ Constructor
In C++, constructor is a special method which is invoked automatically at the time of object
creation. It is used to initialize the data members of new object generally. The constructor in C++
has the same name as class or structure.
o Default constructor
o Parameterized constructor
#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Default Constructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2;
return 0;
}
C++ Parameterized Constructor
A constructor which has parameters is called parameterized constructor. It is used to provide
different values to distinct objects.
#include <iostream>
class A {
private:
public:
num1 = n1;
num2 = n2;
}
void display() {
}
};
int main() {
A obj(3,8);
obj.display();
return 0;
C++ Destructor
A destructor works opposite to constructor; it destructs the objects of classes. It can be defined
only once in a class. Like constructors, it is invoked automatically.
A destructor is defined like constructor. It must have same name as class. But it is prefixed with a
tilde sign (~).
#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Constructor Invoked"<<endl;
}
~Employee()
{
cout<<"Destructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
return 0;
}
#include <iostream>
using namespace std;
class Employee {
public:
int id; //data member (also instance variable)
string name; //data member(also instance variable)
float salary;
Employee(int id, string name, float salary)
{
this->id = id;
this->name = name;
this->salary = salary;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee
Employee e2=Employee(102, "Nakul", 59000); //creating an object of Employee
e1.display();
e2.display();
return 0;
}
C++ static
In C++, static is a keyword or modifier that belongs to the type not instance. So instance is not
required to access the static members. In C++, static can be field, method, constructor, class,
properties, operator and event.
It is used to refer the common property of all objects such as rateOfInterest in case of Account,
companyName in case of Employee etc.
#include <iostream>
using namespace std;
class Account {
public:
int accno; //data member (also instance variable)
string name; //data member(also instance variable)
static float rateOfInterest;
Account(int accno, string name)
{
this->accno = accno;
this->name = name;
}
void display()
{
cout<<accno<< "<<name<< " "<<rateOfInterest<<endl;
}
};
float Account::rateOfInterest=6.5;
int main(void) {
Account a1 =Account(201, "Sanjay"); //creating an object of Employee
Account a2=Account(202, "Nakul"); //creating an object of Employee
a1.display();
a2.display();
return 0;
}
#include <iostream>
using namespace std;
class Account {
public:
int accno; //data member (also instance variable)
string name;
static int count;
Account(int accno, string name)
{
this->accno = accno;
this->name = name;
count++;
}
void display()
{
cout<<accno<<" "<<name<<endl;
}
};
int Account::count=0;
int main(void) {
Account a1 =Account(201, "Sanjay"); //creating an object of Account
Account a2=Account(202, "Nakul");
Account a3=Account(203, "Ranjana");
a1.display();
a2.display();
a3.display();
cout<<"Total Objects are: "<<Account::count;
return 0;
}
C++ Structs
In C++, classes and structs are blueprints that are used to create the instance of a class. Structs
are used for lightweight objects such as Rectangle, color, Point, etc.
Unlike class, structs in C++ are value type than reference type. It is useful if you have data that is
not intended to be modified after creation of struct.
C++ Structure is a collection of different data types. It is similar to the class that holds different
types of data.
struct Student
{
char name[20];
int id;
int age;
}
In the above case, Student is a structure contains three variables name, id, and age. When the
structure is declared, no memory is allocated. When the variable of a structure is created, then the
memory is allocated. Let's understand this scenario.
Student s;
Here, s is a structure variable of type Student. When the structure variable is created, the memory
will be allocated. Student structure contains one char variable and two integer variable. Therefore,
the memory for one char variable is 1 byte and two ints will be 2*4 = 8. The total memory
occupied by the s variable is 9 byte.
s.id = 4;
In the above statement, we are accessing the id field of the structure Student by using
the dot(.) operator and assigns the value 4 to the id field.
Struct Rectangle which has two data members width and height.
#include <iostream>
using namespace std;
struct Rectangle
{
int width, height;
};
int main(void) {
struct Rectangle rec;
rec.width=8;
rec.height=5;
cout<<"Area of Rectangle is: "<<(rec.width * rec.height)<<endl;
return 0;
}
#include <iostream>
using namespace std;
struct Rectangle {
int width, height;
Rectangle(int w, int h)
{
width = w;
height = h;
}
void areaOfRectangle() {
cout<<"Area of Rectangle is: "<<(width*height); }
};
int main(void) {
struct Rectangle rec=Rectangle(4,6);
rec.areaOfRectangle();
return 0;
}
C++ Enumeration
Enum in C++ is a data type that contains fixed set of constants.
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST) etc. The C++ enum
constants are static and final implicitly.
C++ Enums can be thought of as classes that have fixed set of constants.
#include <iostream>
using namespace std;
enum week { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };
int main()
{
week day;
day = Friday;
cout << "Day: " << day+1<<endl;
return 0;
}
By using the keyword friend compiler knows the given function is a friend function.
For accessing the data, the declaration of a friend function should be done inside the body of a
class starting with the keyword friend.
in the above declaration, the friend function is preceded by the keyword friend. The function can be
defined anywhere in the program like a normal C++ function. The function definition does not use
either the keyword friend or scope resolution operator.
o The function is not in the scope of the class to which it has been declared as a friend.
o It cannot be called using the object as it is not in the scope of that class.
o It can be invoked like a normal function without using the object.
o It cannot access the member names directly and has to use an object name and dot
membership operator with the member name.
o It can be declared either in the private or the public part.
#include <iostream>
using namespace std;
class Box
{
private:
int length;
public:
Box(): length(0) { }
friend int printLength(Box); //friend function
};
int printLength(Box b)
{
b.length += 10;
return b.length;
}
int main()
{
Box b;
cout<<"Length of box: "<< printLength(b)<<endl;
return 0;
}
Power functions
Method Description
llround(x) It rounds off the value of x and cast to long long integer.
lrint(x) It rounds off the value of x using rounding mode and cast to long integer.
llrint(x) It rounds off the value x and cast to long long integer.
C++ Inheritance
In C++, inheritance is a process in which one object acquires all the properties and behaviors of
its parent object automatically. In such way, you can reuse, extend or modify the attributes and
behaviors which are defined in other class.
In C++, the class which inherits the members of another class is called derived class and the class
whose members are inherited is called base class. The derived class is the specialized class for the
base class.
Types Of Inheritance
C++ supports five types of inheritance:
Single inheritance
Multiple inheritance
Hierarchical inheritance
Multilevel inheritance
Hybrid inheritance
Derived Classes
A Derived class is defined as the class derived from the base class.
class derived_class_name :: visibility-mode base_class_name
{
// body of the derived class.
}
Where,
visibility mode: The visibility mode specifies whether the features of the base class are publicly
inherited or privately inherited. It can be public or private.
o When the base class is privately inherited by the derived class, public members of the base
class becomes the private members of the derived class. Therefore, the public members of
the base class are not accessible by the objects of the derived class only by the member
functions of the derived class.
o When the base class is publicly inherited by the derived class, public members of the base
class also become the public members of the derived class. Therefore, the public members
of the base class are accessible by the objects of the derived class as well as by the member
functions of the base class.
Note:
o In C++, the default mode of visibility is private.
o The private members of the base class are never inherited.
Where 'A' is the base class, and 'B' is the derived class.
#include <iostream>
using namespace std;
class Account {
public:
float salary = 60000;
};
class Programmer: public Account {
public:
float bonus = 5000;
};
int main(void) {
Programmer p1;
cout<<"Salary: "<<p1.salary<<endl;
cout<<"Bonus: "<<p1.bonus<<endl;
return 0;
}
#include <iostream>
using namespace std;
class Animal {
public:
void eat() {
cout<<"Eating..."<<endl;
}
};
class Dog: public Animal
{
public:
void bark(){
cout<<"Barking...";
}
};
int main(void) {
Dog d1;
d1.eat();
d1.bark();
return 0;
}
#include <iostream>
using namespace std;
class Animal {
public:
void eat() {
cout<<"Eating..."<<endl;
}
};
class Dog: public Animal
{
public:
void bark(){
cout<<"Barking..."<<endl;
}
};
class BabyDog: public Dog
{
public:
void weep() {
cout<<"Weeping...";
}
};
int main(void) {
BabyDog d1;
d1.eat();
d1.bark();
d1.weep();
return 0;
}
C++ Multiple Inheritance
Multiple inheritance is the process of deriving a new class that inherits the attributes from two
or more classes.
class D : visibility B-1, visibility B-2,
{
// Body of the class;
}
#include <iostream>
using namespace std;
class A
{
protected:
int a;
public:
void get_a(int n)
{
a = n;
}
};
class B
{
protected:
int b;
public:
void get_b(int n)
{
b = n;
}
};
class C : public A,public B
{
public:
void display()
{
std::cout << "The value of a is : " <<a<< std::endl;
std::cout << "The value of b is : " <<b<< std::endl;
cout<<"Addition of a and b is : "<<a+b;
}
};
int main()
{
C c;
c.get_a(10);
c.get_b(20);
c.display();
return 0;
}
In the above example, class 'C' inherits two base classes 'A' and 'B' in a public mode.
Example:
#include <iostream>
using namespace std;
class A
{
public:
void display()
{
std::cout << "Class A" << std::endl;
}
};
class B
{
public:
void display()
{
std::cout << "Class B" << std::endl;
}
};
class C : public A, public B
{
void view()
{
display();
}
};
int main()
{
C c;
c.display();
return 0;
}
o The above issue can be resolved by using the class resolution operator with the function. In
the above example, the derived class code can be rewritten as:
class C : public A, public B
{
void view()
{
A :: display(); // Calling the display() function of class A.
B :: display(); // Calling the display() function of class B.
}
};
Example:
#include <iostream>
using namespace std;
class A
{
protected:
int a;
public:
void get_a()
{
std::cout << "Enter the value of 'a' : " << std::endl;
cin>>a;
}
};
class B : public A
{
protected:
int b;
public:
void get_b()
{
std::cout << "Enter the value of 'b' : " << std::endl;
cin>>b;
}
};
class C
{
protected:
int c;
public:
void get_c()
{
std::cout << "Enter the value of c is : " << std::endl;
cin>>c;
}
};
class D : public B, public C
{
protected:
int d;
public:
void mul()
{
get_a();
get_b();
get_c();
std::cout << "Multiplication of a,b,c is : " <<a*b*c<< std::endl;
}
};
int main()
{
D d;
d.mul();
return 0;
}
class A
{
// body of the class A.
}
class B : public A
{
// body of class B.
}
class C : public A
{
// body of class C.
}
class D : public A
{
// body of class D.
}
Example:
#include <iostream>
using namespace std;
class Shape // Declaration of base class.
{
public:
int a;
int b;
void get_data(int n,int m)
{
a= n;
b = m;
}
};
class Rectangle : public Shape // inheriting Shape class
{
public:
int rect_area()
{
int result = a*b;
return result;
}
};
class Triangle : public Shape // inheriting Shape class
{
public:
int triangle_area()
{
float result = 0.5*a*b;
return result;
}
};
int main()
{
Rectangle r;
Triangle t;
int length,breadth,base,height;
std::cout << "Enter the length and breadth of a rectangle: " << std::endl;
cin>>length>>breadth;
r.get_data(length,breadth);
int m = r.rect_area();
std::cout << "Area of the rectangle is : " <<m<< std::endl;
std::cout << "Enter the base and height of the triangle: " << std::endl;
cin>>base>>height;
t.get_data(base,height);
float n = t.triangle_area();
std::cout <<"Area of the triangle is : " << n<<std::endl;
return 0;
}
C++ Polymorphism
The term "Polymorphism" is the combination of "poly" + "morphs" which means many forms. It is
a greek word. In object-oriented programming, we use 3 main concepts: inheritance,
encapsulation, and polymorphism.
class A // base class declaration.
{
int a;
public:
void display()
{
cout<< "Class A ";
}
};
class B : public A // derived class declaration.
{
int b;
public:
void display()
{
cout<<"Class B";
}
};
In the above case, the prototype of display() function is the same in both the base and derived
class. Therefore, the static binding cannot be applied. It would be great if the appropriate
function is selected at the run time. This is known as run time polymorphism.
74.3K
2. Objects in PHP | Build a CMS using OOP PHP tutorial MVC [2020]
o Run time polymorphism: Run time polymorphism is achieved when the object's method is
invoked at the run time instead of compile time. It is achieved by method overriding which is
also known as dynamic binding or late binding.
Differences b/w compile time and run time polymorphism.
The function to be invoked is known at the compile The function to be invoked is known at the run
time. time.
It is also known as overloading, early binding and It is also known as overriding, Dynamic
static binding. binding and late binding.
Overloading is a compile time polymorphism where Overriding is a run time polymorphism where
more than one method is having the same name but more than one method is having the same
with the different number of parameters or the type name, number of parameters and the type of
of the parameters. the parameters.
It is achieved by function overloading and operator It is achieved by virtual functions and pointers.
overloading.
It provides fast execution as it is known at the It provides slow execution as it is known at the
compile time. run time.
It is less flexible as mainly all the things execute at It is more flexible as all the things execute at
the compile time. the run time.
#include <iostream>
using namespace std;
class Animal {
public:
void eat(){
cout<<"Eating...";
}
};
class Dog: public Animal
{
public:
void eat()
{ cout<<"Eating bread...";
}
};
int main(void) {
Dog d = Dog();
d.eat();
return 0;
}
#include <iostream>
using namespace std;
class Shape { // base class
public:
virtual void draw(){ // virtual function
cout<<"drawing..."<<endl;
}
};
class Rectangle: public Shape // inheriting Shape class.
{
public:
void draw()
{
cout<<"drawing rectangle..."<<endl;
}
};
class Circle: public Shape // inheriting Shape class.
{
public:
void draw()
{
cout<<"drawing circle..."<<endl;
}
};
int main(void) {
Shape *s; // base class pointer.
Shape sh; // base class object.
Rectangle rec;
Circle cir;
s=&sh;
s->draw();
s=&rec;
s->draw();
s=?
s->draw();
}
o methods,
o constructors, and
o indexed properties
The advantage of Function overloading is that it increases the readability of the program because
you don't need to use different names for the same action.
#include <iostream>
using namespace std;
class Cal {
public:
static int add(int a,int b){
return a + b;
}
static int add(int a, int b, int c)
{
return a + b + c;
}
};
int main(void) {
Cal C; // class object declaration.
cout<<C.add(10, 20)<<endl;
cout<<C.add(12, 20, 23);
return 0;
}
#include<iostream>
using namespace std;
int mul(int,int);
float mul(float,int);
int mul(int a,int b)
{
return a*b;
}
float mul(double x, int y)
{
return x*y;
}
int main()
{
int r1 = mul(6,7);
float r2 = mul(0.2,3);
std::cout << "r1 is : " <<r1<< std::endl;
std::cout <<"r2 is : " <<r2<< std::endl;
return 0;
}
The advantage of Operators overloading is to perform different operations on the same operand.
Operator that cannot be overloaded are as follows:
operator op is an operator function where op is the operator being overloaded, and the operator
is the keyword.
#include <iostream>
using namespace std;
class Test
{
private:
int num;
public:
Test(): num(8){}
void operator ++() {
num = num+2;
}
void Print() {
cout<<"The Count is: "<<num;
}
};
int main()
{
Test tt;
++tt; // calling of a function "void operator ++()"
tt.Print();
return 0;
}
#include <iostream>
using namespace std;
class A
{
int x;
public:
A(){}
A(int i)
{
x=i;
}
void operator+(A);
void display();
};
void A :: operator+(A a)
{
int m = x+a.x;
cout<<"The result of the addition of two objects is : "<<m;
}
int main()
{
A a1(5);
A a2(4);
a1+a2;
return 0;
}
#include <iostream>
using namespace std;
class Animal {
public:
void eat(){
cout<<"Eating...";
}
};
class Dog: public Animal
{
public:
void eat()
{
cout<<"Eating bread...";
}
};
int main(void) {
Dog d = Dog();
d.eat();
return 0;
}
#include <iostream>
using namespace std;
class A
{
int x=5;
public:
void display()
{
std::cout << "Value of x is : " << x<<std::endl;
}
};
class B: public A
{
int y = 10;
public:
void display()
{
std::cout << "Value of y is : " <<y<< std::endl;
}
};
int main()
{
A *a;
B b;
a = &b;
a->display();
return 0;
}
C++ virtual function Example
Example of C++ virtual function used to invoked the derived class in a program.
#include <iostream>
{
public:
virtual void display()
{
cout << "Base class is invoked"<<endl;
}
};
class B:public A
{
public:
void display()
{
cout << "Derived Class is invoked"<<endl;
}
};
int main()
{
A* a; //pointer of base class
B b; //object of derived class
a = &b;
a->display(); //Late Binding occurs
}
virtual void display() = 0;
Example:
#include <iostream>
using namespace std;
class Base
{
public:
virtual void show() = 0;
};
class Derived : public Base
{
public:
void show()
{
std::cout << "Derived class is derived from the base class." << std::endl;
}
};
int main()
{
Base *bptr;
//Base b;
Derived d;
bptr = &d;
bptr->show();
return 0;
}
1. Abstract class
2. Interface
Abstract class and interface both can have abstract methods which are necessary for abstraction.
In C++ class is made abstract by declaring at least one of its functions as <>strong>pure virtual
function. A pure virtual function is specified by placing "= 0" in its declaration. Its implementation
must be provided by derived classes.
Example of abstract class in C++ which has one abstract method draw(). Its implementation is
provided by derived classes: Rectangle and Circle. Both classes have different implementation.
#include <iostream>
using namespace std;
class Shape
{
public:
virtual void draw()=0;
};
class Rectangle : Shape
{
public:
void draw()
{
cout < <"drawing rectangle..." < <endl;
}
};
class Circle : Shape
{
public:
void draw()
{
cout <<"drawing circle..." < <endl;
}
};
int main( ) {
Rectangle rec;
Circle cir;
rec.draw();
cir.draw();
return 0;
}
C++ Namespaces
Namespaces in C++ are used to organize too many classes so that it can be easy to handle the
application.
In C++, global namespace is the root namespace. The global::std will always refer to the
namespace "std" of C++ Framework.
#include <iostream>
using namespace std;
namespace First {
void sayHello() {
cout<<"Hello First Namespace"<<endl;
}
}
namespace Second {
void sayHello() {
cout<<"Hello Second Namespace"<<endl;
}
}
int main()
{
First::sayHello();
Second::sayHello();
return 0;
#include <iostream>
using namespace std;
namespace First{
void sayHello(){
cout << "Hello First Namespace" << endl;
}
}
namespace Second{
void sayHello(){
cout << "Hello Second Namespace" << endl;
}
}
using namespace First;
int main () {
sayHello();
return 0;
}
C++ Strings
In C++, string is an object of std::string class that represents sequence of characters. We can
perform many operations on strings such as concatenation, comparison, conversion etc.
#include <iostream>
using namespace std;
int main( ) {
string s1 = "Hello";
char ch[] = { 'C', '+', '+'};
string s2 = string(ch);
cout<<s1<<endl;
cout<<s2<<endl;
}
#include <iostream>
#include <cstring>
using namespace std;
int main ()
{
char key[] = "mango";
char buffer[50];
do {
cout<<"What is my favourite fruit? ";
cin>>buffer;
} while (strcmp (key,buffer) != 0);
cout<<"Answer is correct!!"<<endl;
return 0;
}
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char key[25], buffer[25];
cout << "Enter the key string: ";
cin.getline(key, 25);
cout << "Enter the buffer string: ";
cin.getline(buffer, 25);
strcat(key, buffer);
cout << "Key = " << key << endl;
cout << "Buffer = " << buffer<<endl;
return 0;
}
C++ String Copy Example
Example of copy the string using strcpy() function.
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char key[25], buffer[25];
cout << "Enter the key string: ";
cin.getline(key, 25);
strcpy(buffer, key);
cout << "Key = "<< key << endl;
cout << "Buffer = "<< buffer<<endl;
return 0;
}
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char ary[] = "Welcome to C++ Programming";
cout << "Length of String = " << strlen(ary)<<endl;
return 0;
}
In C++, exception is an event or object which is thrown at runtime. All exceptions are derived
from std::exception class. It is a runtime error which can be handled. If we don't handle the
exception, it prints exception message and terminates the program.
Advantage
It maintains the normal flow of the application. In such case, rest of the code is executed even
after exception.
C++ Exception Classes
In C++ standard exceptions are defined in <exception> class that we can use inside our
programs. The arrangement of parent-child class hierarchy is shown below:
All the exception classes in C++ are derived from std::exception class. Let's see the list of C++
common exception classes.
Exception Description
o try
o catch, and
o throw
C++ try/catch
In C++ programming, exception handling is performed using try/catch statement. The C++ try
block is used to place the code that may occur exception. The catch block is used to handle
the exception.
#include <iostream>
using namespace std;
float division(int x, int y) {
if( y == 0 ) {
throw "Attempted to divide by zero!";
}
return (x/y);
}
int main () {
int i = 25;
int j = 0;
float k = 0;
try {
k = division(i, j);
cout << k << endl;
}catch (const char* e) {
cerr << e << endl;
}
return 0;
}
#include <iostream>
#include <exception>
using namespace std;
class MyException : public exception{
public:
const char * what() const throw()
{
return "Attempted to divide by zero!\n";
}
};
int main()
{
try
{
int x, y;
cout << "Enter the two numbers : \n";
cin >> x >> y;
if (y == 0)
{
MyException z;
throw z;
}
else
{
cout << "x / y = " << x/y << endl;
}
}
catch(exception& e)
{
cout << e.what();
}
}
To read and write from a file we are using the standard C++ library called fstream. Let us see the
data types define in fstream library is:
fstream It is used to create files, write information to files, and read information from files.
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream filestream("testout.txt");
if (filestream.is_open())
{
filestream << "Welcome to javaTpoint.\n";
filestream << "C++ Tutorial.\n";
filestream.close();
}
else cout <<"File opening is fail.";
return 0;
}
#include <iostream>
#include <fstream>
using namespace std;
int main () {
string srg;
ifstream filestream("testout.txt");
if (filestream.is_open())
{
while ( getline (filestream,srg) )
{
cout << srg <<endl;
}
filestream.close();
}
else {
cout << "File opening is fail."<<endl;
}
return 0;
}
#include <fstream>
#include <iostream>
using namespace std;
int main () {
char input[75];
ofstream os;
os.open("testout.txt");
cout <<"Writing to a text file:" << endl;
cout << "Please Enter your name: ";
cin.getline(input, 100);
os << input << endl;
cout << "Please Enter your age: ";
cin >> input;
cin.ignore();
os << input << endl;
os.close();
ifstream is;
string line;
is.open("testout.txt");
cout << "Reading from a text file:" << endl;
while (getline (is,line))
{
cout << line << endl;
}
is.close();
return 0;
}
C++ getline()
The cin is an object which is used to take input from the user but does not allow to take the input
in multiple lines. To accept the multiple lines, we use the getline() function. It is a pre-defined
function defined in a <string.h> header file used to accept a line or a string from the input
stream until the delimiting character is encountered.
istream& getline( istream& is, string& str, char delim );
Where,
s: It is an object of the istream class that defines from where to read the input stream.
Return value
This function returns the input stream object, which is passed as a parameter to the function.
The above syntax contains two parameters, i.e., is and str. This syntax is almost similar to the
above syntax; the only difference is that it does not have any delimiting character.
Where,
is: It is an object of the istream class that defines from where to read the input stream.
Return value
This function also returns the input stream, which is passed as a parameter to the function.
Example.
First, we will look at an example where we take the user input without using getline() function.
#include <iostream>
#include<string.h>
using namespace std;
int main()
{
string name; // variable declaration
std::cout << "Enter your name :" << std::endl;
cin>>name;
cout<<"\nHello "<<name;
return 0;
}
In the above code, we take the user input by using the statement cin>>name, i.e., we have not used
the getline() function.
Output:
In the above output, we gave the name 'John Miller' as user input, but only 'John' was displayed.
Therefore, we conclude that cin does not consider the character when the space character is
encountered.
#include <iostream>
#include<string.h>
using namespace std;
int main()
{
string name; // variable declaration.
std::cout << "Enter your name :" << std::endl;
getline(cin,name); // implementing a getline() function
cout<<"\nHello "<<name;
return 0;
}
In the above code, we have used the getline() function to accept the character even when the space
character is encountered.
Enter your
Output:
In the above output, we can observe that both the words, i.e., John and Miller, are displayed, which
means that the getline() function considers the character after the space character also.
When we do not want to read the character after space then we use the following code:
#include <iostream>
#include<string.h>
using namespace std;
int main()
{
string profile; // variable declaration
std::cout << "Enter your profile :" << std::endl;
getline(cin,profile,' '); // implementing getline() function with a delimiting character.
cout<<"\nProfile is :"<<profile;
}
C++ Templates
A C++ template is a powerful feature added to C++. It allows you to define the generic classes
and generic functions and thus provides support for generic programming. Generic programming
is a technique where generic types are used as parameters in algorithms so that they can work for
a variety of data types.
o Function templates
o Class templates
Function Templates:
We can define a template for a function. For example, if we have an add() function, we can create
versions of the add function for adding the int, float or double type values.
Class Template:
We can define a template for a class. For example, a class template can be created for the array
class that can accept the array of various types such as int array, float array or double array.
Function Template
o Generic functions use the concept of a function template. Generic functions define a set of
operations that can be applied to the various types of data.
o The type of the data that the function will operate on depends on the type of the data
passed as a parameter.
o For example, Quick sorting algorithm is implemented using a generic function, it can be
implemented to an array of integers or array of floats.
o A Generic function is created by using the keyword template. The template defines what
function will do.
template < class Ttype> ret_type func_name(parameter_list)
{
// body of function.
}
Where Ttype: It is a placeholder name for a data type used by the function. It is used within the
function definition. It is only a placeholder that the compiler will automatically replace this
placeholder with the actual data type.
#include <iostream>
using namespace std;
template<class T> T add(T &a,T &b)
{
T result = a+b;
return result;
}
int main()
{
int i =2;
int j =3;
float m = 2.3;
float n = 1.2;
cout<<"Addition of i and j is :"<<add(i,j);
cout<<'\n';
cout<<"Addition of m and n is :"<<add(m,n);
return 0;
}
In the above example, we create the function template which can perform the addition operation on
any type either it can be integer, float or double.
Syntax
template<class T1, class T2,.....>
return_type function_name (arguments of type T1, T2....)
{
// body of function.
}
In the above syntax, we have seen that the template function can accept any number of
arguments of a different type.
Example:
#include <iostream>
using namespace std;
template<class X,class Y> void fun(X a,Y b)
{
std::cout << "Value of a is : " <<a<< std::endl;
std::cout << "Value of b is : " <<b<< std::endl;
}
int main()
{
fun(15,12.3);
return 0;
}
In the above example, we use two generic types in the template function, i.e., X and Y.
Example:
#include <iostream>
using namespace std;
template<class X> void fun(X a)
{
std::cout << "Value of a is : " <<a<< std::endl;
}
template<class X,class Y> void fun(X b ,Y c)
{
std::cout << "Value of b is : " <<b<< std::endl;
std::cout << "Value of c is : " <<c<< std::endl;
}
int main()
{
fun(10);
fun(20,30.5);
return 0;
}
In the above example, template of fun() function is overloaded.
Example:
#include <iostream>
using namespace std;
void fun(double a)
{
cout<<"value of a is : "<<a<<'\n';
}
void fun(int b)
{
if(b%2==0)
{
cout<<"Number is even";
}
else
{
cout<<"Number is odd";
}
}
int main()
{
fun(4.6);
fun(6);
return 0;
}
In the above example, we overload the ordinary functions. We cannot overload the generic
functions as both the functions have different functionalities. First one is displaying the value and
the second one determines whether the number is even or not.
CLASS TEMPLATE
Class Template can also be defined similarly to the Function Template. When a class uses the
concept of Template, then the class is known as generic class.
Syntax
template<class Ttype>
class class_name
{
.
.
}
Ttype is a placeholder name which will be determined when the class is instantiated. We can
define more than one generic data type using a comma-separated list. The Ttype can be used
inside the class body.
class_name<type> ob;
type: It is the type of the data that the class is operating on.
Example:
#include <iostream>
using namespace std;
template<class T>
class A
{
public:
T num1 = 5;
T num2 = 6;
void add()
{
std::cout << "Addition of num1 and num2 : " << num1+num2<<std::endl;
}
};
int main()
{
A<int> d;
d.add();
return 0;
}
In the above example, we create a template for class A. Inside the main() method, we create the
instance of class A named as, 'd'.
Syntax
template<class T1, class T2, ......>
class class_name
{
// Body of the class.
}
#include <iostream>
using namespace std;
template<class T1, class T2>
class A
{
T1 a;
T2 b;
public:
A(T1 x,T2 y)
{
a = x;
b = y;
}
void display()
{
std::cout << "Values of a and b are : " << a<<" ,"<<b<<std::endl;
}
};
int main()
{
A<int,float> d(5,6.5);
d.display();
return 0;
}