Object Oriented Progra
Object Oriented Progra
What is C++?
C++ gives programmers a high level of control over system resources and memory.
C++ can be found in today's operating systems, Graphical User Interfaces, and embedded systems.
C++ is an object-oriented programming language which gives a clear structure to programs and allows
code to be reused, lowering development costs.
C++ is portable and can be used to develop applications that can be adapted to multiple platforms.
OOP POP
Object functions are linked through message Parts of program are linked through parameter
passing. passing.
OOP POP
Adding new data and functions is easy Expanding new data and functions is not easy.
Use for solving big problems. Not suitable for solving big problems.
float 4 bytes Stores fractional numbers, containing one or more decimals. Sufficient for storing 6-7
decimal digits
double 8 bytes Stores fractional numbers, containing one or more decimals. Sufficient for storing 15
decimal digits
In C++, there are different types of variables (defined with different keywords), for example:
int - stores integers (whole numbers), without decimals, such as 123 or -123
double - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
string - stores text, such as "Hello World". String values are surrounded by double quotes
bool - stores values with two states: true or false
Example:
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
#include <iostream>
int main() {
std :: cout << "Hello World!";
return 0;
}
The std is a short form of standard, the std namespace contains the built-in classes and declared functions.
Namespaces are regions in a program logically separated from the rest. They are necessary if you want
more than one function with the same name. You can declare two different namespaces for these
functions and call them by referencing their corresponding namespace.
It is similar to referencing the second names when two people have the same first name. So namespace
tells the compiler which of the two identically named functions to use.
Namespace in C++ is the declarative part where the scope of identifiers like functions, the name of
types, classes, variables, etc., are declared. The code generally has multiple libraries, and the namespace
helps in avoiding the ambiguity that may occur when two identifiers have the same name.
For example, suppose you have two functions named calculate (), and both are performing different tasks.
One calculate () function is doing the multiplication, and another is doing the addition. So in this case, to
avoid ambiguity, you will declare both the functions in two different namespaces. These namespaces will
differentiate both the functions and also provide information regarding both the functions.
Definition:
namespace namespace_name
int a, b;
The std is a short form of standard, the std namespace contains the built-in classes and declared functions.
You can find all the standard types and functions in the C++ "std" namespace. There are also several
namespaces inside "std."
Example:
Here std is used in front of cin and cout along with scope resolution operator, which indicates that the
object cin and cout are defined inside the namespace whose name is std.
The std is the standard library, and both cin and cout are defined inside this scope.
To define a namespace, first, the namespace keyword is written in the beginning and then the name of the
namespace, and inside the brackets, there are declarations.
Syntax:
Example:
Here, the name of the namespace is the column, and the variable named data is declared as its member.
As you have understood how to define your own namespace, you will now learn how to access the
contents of this namespace.
To access the namespace members, you can use the name of the namespace and the member name, along
with the scope resolution operator.
Syntax:
Example:
Here data variable whose value is 20 is declared in the namespace and another variable data having value
140.57 is declared in the main function. To print both the variables we have to put the namespace name in
front of the data variable having value 20 i.e column::data, otherwise both data variables will print
140.57.
So to print the value of a namespace member, we have to write a namespace with its scope, which will
avoid the name clash.
Input Output function:
cout is pronounced "see-out". Used for output, and uses the insertion operator (<<)
cin is pronounced "see-in". Used for input, and uses the extraction operator (>>)
Example:
int x, y;
int sum;
cout << "Type a number: ";
cin >> x;
cout << "Type another number: ";
cin >> y;
sum = x + y;
cout << "Sum is: " << sum;
Output:
However, cin considers a space (whitespace, tabs, etc) as a terminating character, which means that it can
only store a single word (even if you type many words).
From the example above, you would expect the program to print "John Doe", but it only prints "John".
That's why, when working with strings, we often use the getline() function to read a line of text. It
takes cin as the first parameter, and the string variable as second:
string fullName;
cout << "Type your full name: ";
getline (cin, fullName);
cout << "Your name is: " << fullName;
Output:
Syntax:
for (type variableName : arrayName) {
// code block to be executed
}
Example:
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i : myNumbers) {
cout << i << "\n";
}
Example:
// Create an array of strings
string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
Function:
You can also use a default parameter value, by using the equals sign (=).
If we call the function without an argument, it uses the default value ("Norway"):
Example:
void myFunction(string country = "Norway") {
cout << country << "\n";
}
int main() {
myFunction("Sweden");
myFunction("India");
myFunction();
myFunction("USA");
return 0;
}
// Sweden
// India
// Norway
// USA
A parameter with a default value, is often known as an "optional parameter". From the example
above, country is an optional parameter and "Norway" is the default value.
Class
Object
Encapsulation
Abstraction
Polymorphism
Inheritance
Class:
A Class is a user-defined data type that has data members and member functions.
Data members are the data variables and member functions are the functions used to manipulate
these variables together these data members and member functions define the properties and
behavior of the objects in a Class.
For Example:
Consider the Class of Cars. There may be many cars with different names and brands but all of them
will share some common properties like all of them will have 4 wheels, Speed Limit, Mileage range,
etc. So here, the Car is the class, and wheels, speed limits, and mileage are their properties.
Syntax:
Object:
Object means a real word entity such as pen, chair, table etc.
An Object is an instance of a Class. When a class is defined, no memory is allocated but when it is
instantiated (i.e. an object is created) memory is allocated.
ClassName ObjectName;
Example:
MyClass obj;
The data members and member functions of the class can be accessed using the dot(„.‟) operator with the
object. For example, if the name of the object is obj and you want to access the member function with the
name printName() then you will have to write:
obj.printName()
Class Object
#include <iostream>
using namespace std;
int main()
{
// Create an object of the Person class
Person person1;
return 0;
}
Data Abstraction:
Hiding internal details and showing functionality is known as abstraction. Data abstraction is the
process of exposing to the outside world only the information that is absolutely necessary while
concealing implementation or background information. For example: phone call, we don't know the
internal processing.
Data abstraction refers to providing only essential information to the outside world and hiding their
background details.
Data abstraction is a programming (and design) technique that relies on the separation of interface and
implementation.
Let's take one real life example of a TV, which you can turn on and off, change the channel, adjust the
volume, and add external components such as speakers, VCRs, and DVD players, BUT you do not know
its internal details, that is, you do not know how it receives signals over the air or through a cable, how it
translates them, and finally displays them on the screen.
Thus, we can say a television clearly separates its internal implementation from its external interface and
you can play with its interfaces like the power button, channel changer, and volume control without
having any knowledge of its internals.
In C++, classes provide great level of data abstraction. They provide sufficient public methods to the
outside world to play with the functionality of the object and to manipulate object data, i.e., state without
actually knowing how class has been implemented internally.
For example, your program can make a call to the sort () function without knowing what algorithm the
function actually uses to sort the given values. In fact, the underlying implementation of the sorting
functionality could change between releases of the library, and as long as the interface stays the same,
your function call will still work.
In C++, we use classes to define our own abstract data types (ADT). You can use the cout object of
class ostream to stream data to standard output like this –
Example:
#include <iostream>
class Adder {
public:
// constructor
Adder(int i = 0) {
total = i;
total += number;
int getTotal() {
return total;
};
private:
int total;
};
int main() {
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
return 0;
Output:
Total 60
Encapsulation:
Binding (or wrapping) code and data together into a single unit is known as encapsulation.
Encapsulation is the process of tying together data and the functions that work with it in object-oriented
programming.
Encapsulation is placing the data and the functions that work on that data in the same place. While
working with procedural languages, it is not always clear which functions work on which variables but
object-oriented programming provides you framework to place the data and the relevant functions
together in the same object.
Example:
#include<iostream>
class Box {
public:
length=l;
breadth=b;
height=h;
}
double getVolume(void) {
private:
};
int main()
Box b1;
cout<<area;
Output:
160
Access Specifiers :
Access specifiers define how the members (attributes and methods) of a class can be accessed.
Constructors:
A constructor in C++ is a special method that is automatically called when an object of a class is
created.
It helps to initialize the object of a class.
It is used to allocate the memory to an object of the class.
It can be defined manually with arguments or without arguments.
There can be many constructors in a class.
Characteristics of Constructors in C++:
Constructors are mostly declared in the public section of the class though they can be declared in
the private section of the class.
Constructors do not return values; hence they do not have a return type.
A constructor gets called automatically when we create the object of the class.
To create a constructor, use the same name as the class, followed by parentheses ():
Syntax:
ClassName()
{
//Constructor's Body
}
Example:
#include<iostream>
int main() {
MyClass myObj; // Create an object of MyClass (this will call the constructor)
return 0;
}
1. Default Constructor:
Discussed above.
2. Parameterized Constructor:
Parameterized Constructors make it possible to pass arguments to constructors. Typically, these
arguments help initialize an object when it is created.
Example:
#include <iostream>
using namespace std;
class Point {
private:
int x, y;
public:
// Parameterized Constructor
Point(int x1, int y1)
{
x = x1;
y = y1;
}
int main()
{
// Constructor called
Point p1(10, 15);
return 0;
}
Output:
3. Copy Constructor:
A copy constructor is a member function that initializes an object using another object of the same class.
Example:
#include <iostream>
using namespace std;
A(){};
int main() {
// Creating an a1 object
A a1;
a1.x = 10;
cout << "a1's x = " << a1.x << endl;
return 0;
}
Output:
a1's x = 10
Calling copy constructor
a2's x = 10
Destructors in C++:
Characteristics of a Destructor:
A destructor is also a special member function like a constructor. Destructor destroys the
class objects created by the constructor.
Destructor has the same name as their class name preceded by a tilde (~) symbol.
The destructor is only one way to destroy the object created by the constructor. Hence,
destructor cannot be overloaded.
Destructor release memory space occupied by the objects created by the constructor.
Example:
#include <iostream>
using namespace std;
class Test {
public:
// User-Defined Constructor
Test() { cout << "\n Constructor executed"; }
// User-Defined Destructor
~Test() { cout << "\nDestructor executed"; }
};
int main()
{
Test t;
return 0;
}
Inheritance:
Inheritance is a feature or a process in which, new classes are created from the existing classes. The new
class created is called “derived class” or “child class” and the existing class is known as the “base
class” or “parent class”. The derived class now is said to be inherited from the base class.
When we say derived class inherits the base class, it means that the derived class inherits all the
properties of the base class, without changing the properties of base class and may add new features to its
own.
Sub Class: The class that inherits properties from another class is called Subclass or Derived
Class.
Super Class: The class whose properties are inherited by a subclass is called Base Class or
Superclass.
Consider a group of vehicles. You need to create classes for Bus, Car, and Truck. The methods
fuelAmount(), capacity(), applyBrakes() will be the same for all three classes. If we create these classes
without inheritance, then we have to write all of these functions in each of the three classes as shown
below figure:
You can clearly see that the above process results in duplication of the same code 3 times. This increases
the chances of error and data redundancy. To avoid this type of situation, inheritance is used. If we create
a class Vehicle and write these three functions in it and inherit the rest of the classes from the vehicle
class, then we can simply avoid the duplication of data and increase re-usability. Look at the below
diagram in which the three classes are inherited from vehicle class:
Using inheritance, we have to write the functions only one time instead of three times as we have
inherited the rest of the three classes from the base class (Vehicle).
where,
access-specifier: Specifies the access mode which can be either of private, public or protected. If
neither is specified, private is taken as default.
is-a relationship:
Inheritance is an is-a relationship. We use inheritance only if an is-a relationship is present between the
two classes.
A car is a vehicle.
Orange is a fruit.
A surgeon is a doctor.
A dog is an animal.
Mode of inheritance controls the access level of the inherited members of the base class in the
derived class. In C++, there are 3 modes of inheritance:
Public Mode
Protected Mode
Private Mode
If we derive a subclass from a public base class. Then the public member of the base class will
become public in the derived class and protected members of the base class will become protected in
the derived class.
Example:
If we derive a subclass from a Protected base class. Then both public members and protected
members of the base class will become protected in the derived class.
Example:
If we derive a subclass from a Private base class. Then both public members and protected members
of the base class will become private in the derived class. They can only be accessed by the member
functions of the derived class.
Private mode is the default mode that is applied when we don‟t specify any mode.
Example:
Example 1: Program to show different kinds of Inheritance Modes and their Member Access Levels
class A {
public:
int x;
protected:
int y;
private:
int z;
};
class B : public A {
// x is public
// y is protected
// z is not accessible from B
};
class C : protected A {
// x is protected
// y is protected
// z is not accessible from C
};
#include <iostream>
using namespace std;
class Base {
private:
int pvt = 1;
protected:
int prot = 2;
public:
int pub = 3;
int main() {
PublicDerived object1;
cout << "Private = " << object1.getPVT() << endl;
cout << "Protected = " << object1.getProt() << endl;
cout << "Public = " << object1.pub << endl;
return 0;
}
Output:
Private = 1
Protected = 2
Public = 3
#include <iostream>
using namespace std;
class Base {
private:
int pvt = 1;
protected:
int prot = 2;
public:
int pub = 3;
int main() {
ProtectedDerived object1;
cout << "Private cannot be accessed." << endl;
cout << "Protected = " << object1.getProt() << endl;
cout << "Public = " << object1.getPub() << endl;
return 0;
}
Output
private protected
Accessibility public members
members members
class Base {
private:
int pvt = 1;
protected:
int prot = 2;
public:
int pub = 3;
int main() {
PrivateDerived object1;
cout << "Private cannot be accessed." << endl;
cout << "Protected = " << object1.getProt() << endl;
cout << "Public = " << object1.getPub() << endl;
return 0;
}
Output:
The inheritance can be classified on the basis of the relationship between the derived class and the base
class. In C++, we have 5 types of inheritances:
1. Single inheritance
2. Multilevel inheritance
3. Multiple inheritance
4. Hierarchical inheritance
5. Hybrid inheritance
1. Single Inheritance
In single inheritance, a class is allowed to inherit from only one class. i.e. one base class is inherited by
one derived class only.
Syntax
Example:
class A
{
... .. ...
};
class B: public A
{
... .. ...
};
Implementation:
#include <iostream>
using namespace std;
// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};
// main function
int main()
{
// Creating object of sub class will invoke the constructor of base classes
Car obj;
return 0;
}
Output
This is a Vehicle
This Vehicle is Car
2. Multiple Inheritance
Multiple Inherita nce is a feature of C++ where a class can inherit from more than one class. i.e
one subclass is inherited from more than one base class.
Syntax
Here, the number of base classes will be separated by a comma („, „) and the access mode for every
base class must be specified and can be different.
Example:
class A
{
... .. ...
};
class B
{
... .. ...
};
class C: public A, public B
{
... ... ...
};
Implementation:
#include <iostream>
using namespace std;
// main function
int main()
{
// Creating object of sub class will invoke the constructor of base classes.
Car obj;
return 0;
}
Output:
This is a Vehicle
This is a 4 Wheeler
This 4 Wheeler Vehical is a Car
3. Multilevel Inheritance:
In this type of inheritance, a derived class is created from another derived class and that derived class
can be derived from a base class or any other derived class. There can be any number of levels.
Syntax
Example:
class C
{
... .. ...
};
class B : public C
{
... .. ...
};
class A: public B
{
... ... ...
};
Implementation:
#include <iostream>
using namespace std;
// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};
// main function
int main()
{
// Creating object of sub class will invoke the constructor of base classes.
Car obj;
return 0;
}
Output:
This is a Vehicle
4 Wheeler Vehicles
This 4 Wheeler Vehical is a Car
4. Hierarchical Inheritance:
In this type of inheritance, more than one subclass is inherited from a single base class. i.e. more than one
derived class is created from a single base class.
Syntax:
Example:
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.
}
Implementation
#include <iostream>
using namespace std;
// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};
// main function
int main()
{
// Creating object of sub class will invoke the constructor of base class.
Car obj1;
Bus obj2;
return 0;
}
Output
This is a Vehicle
This Vehicle is Car
This is a Vehicle
This Vehicle is Bus
5. Hybrid Inheritance
Hybrid Inheritance is implemented by combining more than one type of inheritance. For example:
Combining Hierarchical inheritance and Multiple Inheritance will create hybrid inheritance in C++
There is no particular syntax of hybrid inheritance. We can just combine two of the above inheritance
types.
Example:
Below image shows one of the combinations of hierarchical and multiple inheritances:
class F
{
... .. ...
}
class G
{
... .. ...
}
class B : public F
{
... .. ...
}
class E : public F, public G
{
... .. ...
}
class A : public B {
... .. ...
}
class C : public B {
... .. ...
}
Implementation:
#include <iostream>
using namespace std;
// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};
// base class
class Fare {
public:
Fare() { cout << "Fare of Vehicle\n"; }
};
// main function
int main()
{
// Creating object of sub class will invoke the constructor of base class.
Bus obj2;
return 0;
}
Output:
This is a Vehicle
Fare of Vehicle
This Vehicle is a Bus with Fare
Note:
Order of constructor call for Multiple Inheritance:
For multiple inheritance order of constructor call is, the base class‟s constructors are called in the order
of inheritance and then the derived class‟s constructor.
A man at the same time is a father, a husband, and an employee. So the same person exhibits different
behavior in different situations. This is called polymorphism. Polymorphism is considered one of the
important features of Object-Oriented Programming.
Types of Polymorphism:
Compile-time Polymorphism
Runtime Polymorphism
1. Compile-Time Polymorphism:
A. Function Overloading:
When there are multiple functions with the same name but different parameters, then the functions are said
to be overloaded, hence this is known as Function Overloading. Functions can be overloaded by changing
the number of arguments or/and changing the type of arguments and changing order of arguments. In
simple terms, it is a feature of object-oriented programming providing many functions that have the same
name but distinct parameters when numerous tasks are listed under one function name. There are certain
Rules of Function Overloading that should be followed while overloading a function.
Output:
value of x is 7
value of x is 9.132
value of x and y is 85.89, 64
value of x and y is 10, 20.78
Explanation: In the above example, a single function named function func() acts differently in three
different situations, which is a property of polymorphism.
B. Operator Overloading:
C++ has the ability to provide the operators with a special meaning for a data type, this ability is known
as operator overloading. For example, we can make use of the addition operator (+) for string class to
concatenate two strings. We know that the task of this operator is to add two operands. So a single
operator „+‟, when placed between integer operands, adds them and when placed between string
operands, concatenates them.
// Driver code
int main()
{
Complex c1(10, 5), c2(2, 4);
Output:
12 + i9
Explanation: In the above example, the operator „+‟ is overloaded. Usually, this operator is used to add
two numbers (integers or floating point numbers), but here the operator is made to perform the addition of
two imaginary or complex numbers.
2. Runtime Polymorphism:
This type of polymorphism is achieved by Function Overriding. Late binding and dynamic polymorphism
are other names for runtime polymorphism. The function call is resolved at runtime in runtime
polymorphism. In contrast, with compile time polymorphism, the compiler determines which function call
to bind to the object after deducing it at runtime.
A. Function Overriding:
Function Overriding occurs when a derived class has a definition for one of the member functions of the
base class. That base function is said to be overridden.
Function overriding Explanation
Runtime Polymorphism cannot be achieved by data members in C++. Let‟s see an example where we are
accessing the field by reference variable of parent class which refers to the instance of the derived class.
Example:
#include <iostream>
class Animal {
public:
void display()
cout<<"Base="<<color<<endl;
};
public:
string color = "Grey";
void display()
cout<<"Derived="<<color<<endl;
};
// Driver code
int main(void)
d.display();
Output:
Grey
Derived=grey
We can see that the parent class reference will always refer to the data member of the parent class.
Child class object refers its member first if it is available otherwise refers parent class members.
B. Virtual Function:
A virtual function is a member function that is declared in the base class using the keyword virtual and is re-
defined (Overridden) in the derived class.
Example:
Virtual function:
#include <iostream>
class Animal {
public:
string color = "Black";
cout<<"Base="<<color<<endl;
} };
public:
void display()
cout<<"Derived="<<color<<endl;
} };
int main()
Animal *a;
Dog d;
a=&d;
// Animal a;
a->display();
d.display();
If a virtual function is defined in a base class, there is no necessity of redefining it in the derived class.
Friend Class:
A friend class can access private and protected members of other classes in which it is declared as a
friend. It is sometimes useful to allow a particular class to access private and protected members of other
classes. For example, a LinkedList class may be allowed to access private members of Node.
We can declare a friend class in C++ by using the friend keyword.
Syntax:
Example:
#include<iostream>
class A
private:
int x;
protected:
int y;
public:
A(){
x=34;
y=90;
friend class B;
};
class B{
public:
cout<<"x="<<a.x<<endl<<"y="<<a.y<<endl;
};
int main(){
A a;
B b;
b.display(a);
}
Output:
x=34
y=90
Friend function:
Like a friend class, a friend function can be granted special access to private and protected members of a
class in C++. They are not the member functions of the class but can access and manipulate the private and
protected members of that class for they are declared as friends.
A friend function can be:
1. A global function
2. A member function of another class
Syntax:
#include<iostream>
using namespace std;
class A
private:
int x;
protected:
int y;
public:
A(){
x=34;
y=90;
};
void display(A a)
int main(){
A a;
display(a);
Output:
x=34
y=90
Example:
#include <iostream>
class A
int x;
public:
void setdata(int i)
x=i;
};
class B
int y;
public:
void setdata(int i)
y=i;
};
void min(A a, B b)
if(a.x<=b.y)
else
int main()
{
A a;
B b;
a.setdata(10);
b.setdata(20);
min(a,b);
return 0;
Output:
10
#include<iostream>
class A;
class B {
public:
class A {
int a;
public:
a = n1;
};
int main() {
A o1, o2;
o1.setNumber(1);
o2.setNumber(5);
B b;
return 0; }
Output:
The sum is 6
Abstract Class:
An abstract base class has at least one pure virtual function.
Sometimes implementation of all functions cannot be provided in a base class because we don‟t know the
implementation. Such a class is called an abstract class.
For example, let Shape be a base class. We cannot provide the implementation of function draw() in
Shape, but we know every derived class must have an implementation of draw(). Similarly, an Animal
class doesn‟t have the implementation of move() (assuming that all animals move), but all animals must
know how to move.
A pure virtual function (or abstract function) in C++ is a virtual function for which we can have an
implementation, But we must override that function in the derived class, otherwise, the derived class will
also become an abstract class. A pure virtual function is declared by assigning 0 in the declaration.
// An abstract class
class Test {
// Data members of class
public:
// Pure Virtual Function
virtual void show() = 0;
/* Other members */
};
Example:
#include <iostream>
class Base {
public:
};
public:
};
int main()
Derived d;
d.fun();
return 0;
Output:
fun() called
Note:
Example:
struct shapeClass
{
virtual void Draw()=0;
}
Reference variable is an alternate name of already existing variable. It cannot be changed to refer another
variable and should be initialized at the time of declaration and cannot be NULL.
Here,
Example:
#include <iostream>
using namespace std;
int main() {
int a = 8;
int &b = a;
cout << "The variable a : " << a;
cout << "\nThe reference variable r : " << b;
b++;
cout << "The variable a : " << a;
cout << "\nThe reference variable: " << b;
return 0;
}
Output:
The variable a : 8
The reference variable: 8
The variable a : 9
The reference variable: 9
Instance Variable:
An "instance variable" in C++ is a variable declared within a class, outside of any methods, which means
each object created from that class will have its own separate copy of the variable, allowing for unique
data storage within each object; essentially, it defines the state of an object within a class.
#include <iostream>
class Person {
public:
string name;
int age;
};
int main() {
Person person1;
person1.name = "John";
person1.age = 30;
Person person2;
person2.name = "Jane";
person2.age = 25;
return 0;
Explanation:
In this example, "name" and "age" are considered instance variables within the "Person" class.
When you create objects "person1" and "person2", each will have its own separate "name" and "age"
values.
When a static keyword is used, variables, data members, and functions cannot be modified again.
It is allocated for the lifetime of the program. Static functions can be called directly by using a class
name.
Static variables are variables that are defined using static keywords, which consist of special behavior
compared to regular variables. Here we will see its key points.
Syntax:
Here, datatype − The datatype of variables like int, char, float, etc.
variable_name − This is the name of the variable given by the user.
value − Any value to initialize the variable. By default, it is zero.
return_type − The datatype of the function to return the value.
function_name − Any name to the function.
Example:
#include <iostream>
class Box {
public:
// Constructor definition
Box() {
objectCount++;
return objectCount;
};
int Box::objectCount = 0;
int main() {
cout << "Inital Stage Count: " << Box::getCount() << endl;
cout << "Initial Stage Count: " << Box::objectCount << endl;
Box b1,b2;
cout << "Final Stage Count: " << Box::getCount() << endl;
cout << "Final Stage Count: " << Box::objectCount << endl;
return 0;
}
Static object: There is no such thing as a static class in C++. The closest approximation is a class that
only contains static data members and static methods.
Static class means it contains all static data members and member functions.
#include<iostream>
class A{
public:
A(){
cout<<"Constructor called"<<endl;
~A(){
cout<<"Destructor called"<<endl;
};
int main(){
static A a;
cout<<"End of program"<<endl;
return 0;
Output:
Constructor called
End of program
Destructor called