0% found this document useful (0 votes)
22 views38 pages

C Theory

Uploaded by

murugan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views38 pages

C Theory

Uploaded by

murugan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Unit 1

C++ Object and Class


Since C++ is an object-oriented language, program is designed using objects
and classes in C++.

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 a runtime entity, it is created at runtime.

Object is an instance of a class. All the members of the class can be


accessed through object.

Let's see an example to create object of student class using s1 as the


reference variable.

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.

Let's see an example of C++ class that has three fields only.

class Student
{
public:
int id; //field or data member
float salary; //field or data member
String name;//field or data member
}
#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;
}

A class is a user-defined data type, which holds its own data members and
member functions, which can be accessed and used by creating an instance of
that class. A C++ class is like a blueprint for an object.
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.
 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 behaviour of the objects in a Class.

class ClassName {
access_specifier:
// Body of the class
};

class ThisClass {
public:
int var; // data member
void print() { // member method
cout << "Hello";
}
};

C++ Data members and Member functions


PrevNext

A C++ class encapsulates data and behavior into a single unit, allowing for better
organization and modularization of code. The basic structure of a class includes both
data members and member functions.

Data Members
Data members are variables that hold the state of an object. They represent the
attributes or properties of an object. These variables can be of various data types,
including built-in types (int, float, etc.) or user-defined types (other classes, structs).
class Car {
public:
// Data members
string brand;
int year;
float price;
};

In the example above, the Car class has three data members: brand, year, and price.
These variables store information about a car object, such as its brand, manufacturing
year, and price.

Member Functions
Member functions define the behavior of a class. They are responsible for performing
actions or operations related to the class. Member functions can interact with the data
members and are invoked on objects of the class.
class Car {
public:
// Data members
string brand;
int year;
float price;

// Member function to display information about the car


void displayInfo() {
cout << "Brand: " << brand << endl;
cout << "Year: " << year << endl;
cout << "Price: $" << price << endl;
}
};

In the example above, the Car class has a member function called displayInfo(). This
function prints information about the car's brand, year, and price to the console. Member
functions can access the data members of the class directly.

Creating Objects
Once a class is defined, we can create objects (instances) of that class. Objects
represent specific instances of the class and encapsulate the data and behavior defined
in the class.
int main() {
// Create objects of the Car class
Car car1;
Car car2;

// Set values for data members


car1.brand = "Toyota";
car1.year = 2022;
car1.price = 25000.0;

car2.brand = "Honda";
car2.year = 2021;
car2.price = 22000.0;

// Invoke member functions on objects


car1.displayInfo();
cout << "----------------------" << endl;
car2.displayInfo();

return 0;
}

In this example, we create two Car objects, car1 and car2, and set their respective data
members. We then invoke the displayInfo() member function on each object to print
information about the cars to the console.
C++ Access Specifiers
In the previous pages, you may have noticed the use of the public keyword
before the data members and member functions. This is known as an access
specifier and determines the visibility of class members. The three main
access specifiers in C++ are public, private, and protected.
Public Access Specifier
The public access specifier allows members to be accessible from anywhere,
both within the class and externally. Public members define the interface of
the class, and they can be freely accessed by objects of the class and other
parts of the program.
class MyClass {
public:
// Public data member
int publicVar;

// Public member function


void publicMethod() {
// Code for the public method
}
};

Instances of the class can use public members without restrictions:


MyClass myObject;
myObject.publicVar = 42; // Accessing public data member
myObject.publicMethod(); // Calling public member function

Private Access Specifier


The private access specifier restricts access to members to only within the
class. Private members are hidden from external entities, enhancing data
integrity and preventing direct external manipulation.
class MyClass {
private:
// Private data member
int privateVar;

// Private member function


void privateMethod() {
// Code for the private method
}
};
Attempts to access private members from outside the class result in
compilation errors:
MyClass myObject;
// The following lines will cause compilation errors
myObject.privateVar = 42; // Error: 'int MyClass::privateVar' is private
within this context
myObject.privateMethod(); // Error: 'void MyClass::privateMethod()' is private
within this context

By default, members are considered private if no access specifier is specified.


Protected Access Specifier
The protected access specifier, while similar to private, allows access to
derived classes. Protected members maintain encapsulation within the class
but permit derived classes to access and modify them.
class BaseClass {
protected:
// Protected data member
int protectedVar;

// Protected member function


void protectedMethod() {
// Code for the protected method
}
};

Derived classes can access protected members:


class DerivedClass : public BaseClass {
public:
void accessProtectedMembers() {
protectedVar = 42; // Accessing protected data member
protectedMethod(); // Calling protected member function
}
};

Static Data Members


Static data members are class members that are declared
using static keywords. A static member has certain special characteristics
which are as follows:
 Only one copy of that member is created for the entire class and is shared
by all the objects of that class, no matter how many objects are created.
 It is initialized before any object of this class is created, even before the
main starts outside the class itself.
 It is visible can be controlled with the class access specifiers.
 Its lifetime is the entire program.
Syntax
className {
static data_type data_member_name;
.....
}
Example
Below is the C++ program to demonstrate the working of static data
members:
C++

// C++ Program to demonstrate the use of


// static data members
#include <iostream>
using namespace std;

// class definition
class A {
public:
// static data member here
static int x;
A() { cout << "A's constructor called " << endl; }
};

// we cannot initialize the static data member inside the


// class due to class rules and the fact that we cannot
// assign it a value using constructor
int A::x = 2;

// Driver code
int main()
{
// accessing the static data member using scope
// resultion operator
cout << "Accessing static data member: " << A::x
<< endl;

return 0;
}

Output
Accessing static data member: 2

Constructor
Constructor in C++ is a special method that is invoked automatically at the time an
object of a class is created. It is used to initialize the data members of new objects
generally. The constructor in C++ has the same name as the class or structure. It
constructs the values i.e. provides data for the object which is why it is known as a
constructor.
Syntax of Constructors in C++
The prototype of the constructor looks like this:
<class-name> (){
...
}

Characteristics of Constructors in C++


 The name of the constructor is the same as its class name.
 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.
Types of Constructor Definitions in C++
In C++, there are 2 methods by which a constructor can be declared:
1. Defining the Constructor Within the Class
<class-name> (list-of-parameters) {
// constructor definition
}
2. Defining the Constructor Outside the Class
<class-name> {

// Declaring the constructor


// Definiton will be provided outside
<class-name>();

// Defining remaining class


}

<class-name>: :<class-name>(list-of-parameters) {
// constructor definition
}

A particular procedure called a constructor is called automatically when an


object is created in C++. In general, it is employed to create the data
members of new things. In C++, the class or structure name also serves as
the constructor name. When an object is completed, the constructor is
called. Because it creates the values or gives data for the thing, it is known
as a constructor.

The Constructors prototype looks like this:

1. <class-name> (list-of-parameters);
The following syntax is used to define the class's constructor:

1. <class-name> (list-of-parameters) { // constructor definition }

The following syntax is used to define a constructor outside of a class:

1. <class-name>: :<class-name> (list-of-parameters){ // constructor definitio


n}

Constructors lack a return type since they don't have a return value.

There can be two types of constructors in C++.

o Default constructor
o Parameterized constructor

C++ Default Constructor


A constructor which has no argument is known as default constructor. It is
invoked at the time of creating object.

Let's see the simple example of C++ default 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;
}
Output:

Default Constructor Invoked


Default Constructor Invoked

C++ Parameterized Constructor


A constructor which has parameters is called parameterized constructor. It is
used to provide different values to distinct objects.

Let's see the simple example of C++ Parameterized Constructor.

#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 i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};

int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Empl
oyee
Employee e2=Employee(102, "Nakul", 59000);
e1.display();
e2.display();
return 0;
}

Output:

101 Sonoo 890000


102 Nakul 59000

Destructor

Destructor is an instance member function that is invoked automatically whenever


an object is going to be destroyed. Meaning, a destructor is the last function that is
going to be called before an object is destroyed.
In this article, we will learn about the destructors in C++, how they work, how and
why to create the user defined destructors with the code examples. At the end, we
will look at some commonly used questions about C++ destructors.
Syntax to Define Destructor
The syntax for defining the destructor within the class:

~ <class-name>() {
// some instructions
}

Just like any other member function of the class, we can define the destructor
outside the class too:
<class-name> {
public:
~<class-name>();
}

<class-name> :: ~<class-name>() {
// some instructions
}

But we still need to at least declare the destructor inside the class.
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.
 It is not possible to define more than one destructor.
 The destructor is only one way to destroy the object created by the constructor.
Hence, destructor cannot be overloaded.
 It cannot be declared static or const.
 Destructor neither requires any argument nor returns any value.
 It is automatically called when an object goes out of scope.
 Destructor release memory space occupied by the objects created by the
constructor.
 In destructor, objects are destroyed in the reverse of an object creation.
The thing is to be noted here if the object is created by using new or the constructor
uses new to allocate memory that resides in the heap memory or the free store, the
destructor should use delete to free the memory.

Friend function

A friend function of a class is defined outside that class' scope but it has the
right to access all private and protected members of the class. Even though the
prototypes for friend functions appear in the class definition, friends are not
member functions.

A friend can be a function, function template, or member function, or a class or


class template, in which case the entire class and all of its members are friends.
To declare a function as a friend of a class, precede the function prototype in
the class definition with keyword friend as follows −

class Box {
double width;

public:
double length;
friend void printWidth( Box box );
void setWidth( double wid );
};

To declare all member functions of class ClassTwo as friends of class ClassOne,


place a following declaration in the definition of class ClassOne −

friend class ClassTwo;

Consider the following program −

#include <iostream>

using namespace std;

class Box {
double width;

public:
friend void printWidth( Box box );
void setWidth( double wid );
};

// Member function definition


void Box::setWidth( double wid ) {
width = wid;
}

// Note: printWidth() is not a member function of any class.


void printWidth( Box box ) {
/* Because printWidth() is a friend of Box, it can
directly access any member of this class */
cout << "Width of box : " << box.width <<endl;
}
// Main function for the program
int main() {
Box box;

// set box width without member function


box.setWidth(10.0);

// Use friend function to print the wdith.


printWidth( box );

return 0;
}

When the above code is compiled and executed, it produces the following result

Width of box : 10

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:

friend class class_name; // declared in the base class

// C++ Program to demonstrate the


// functioning of a friend class
#include <iostream>
using namespace std;

class GFG {
private:
int private_variable;

protected:
int protected_variable;

public:
GFG()
{
private_variable = 10;
protected_variable = 99;
}

// friend class declaration


friend class F;
};

// Here, class F is declared as a


// friend inside class GFG. Therefore,
// F is a friend of class GFG. Class F
// can access the private members of
// class GFG.
class F {
public:
void display(GFG& t)
{
cout << "The value of Private Variable = "
<< t.private_variable << endl;
cout << "The value of Protected Variable = "
<< t.protected_variable;
}
};

// Driver code
int main()
{
GFG g;
F fri;
fri.display(g);
return 0;
}

Array of Objects in C++


Array of Objects
When a class is defined, only the specification for the object is defined; no memory
or storage is allocated. To use the data and access functions defined in the class, you
need to create objects.
Syntax:
ClassName ObjectName[number of objects];
The Array of Objects stores objects. An array of a class type is also known as an
array of objects.
Example#1:
Storing more than one Employee data. Let’s assume there is an array of objects for
storing employee data emp[50].

/ C++ program to implement


// the above approach
#include<iostream>
using namespace std;

class Employee
{
int id;
char name[30];
public:
void getdata();//Declaration of function
void putdata();//Declaration of function
};
void Employee::getdata(){//Defining of function
cout<<"Enter Id : ";
cin>>id;
cout<<"Enter Name : ";
cin>>name;
}
void Employee::putdata(){//Defining of function
cout<<id<<" ";
cout<<name<<" ";
cout<<endl;
}
int main(){
Employee emp; //One member
emp.getdata();//Accessing the function
emp.putdata();//Accessing the function
return 0;

}
Pointer to object
A pointer to an object in C++ is a variable that contains an
object's memory address. Pointers provide indirect access to and control
over memory items. They are especially helpful when we need to
dynamically allocate memory for objects, build linked lists or trees,
or pass objects by reference to methods without making duplicates.

The behavior of an object pointer is identical to that of a variable pointer.


But in this case, the object's address is kept instead of the variables.
When a class object is formed in the main function, a pointer variable is
declared similarly to the variable itself. Using a data type for the pointer is
not recommended when generating a pointer to an object. Instead, we must
make use of the object pointer's class name. The -> symbol must be used to
call a class member function using a Pointer in the main function.

Accessing Object Members via Pointer:

We can use the arrow operator (->) to access members


(variables and functions) of the object through the pointer.

class myClass
{
public:
void sayHello ()
{
cout << "Hello";
}
};

int main ()
{
myClass* myPointer;
myClass myObject = myClass(* myPointer); // Cast pointer to object
myObject.sayHello();

return 0;
}

C++ this Pointer


Every object in C++ has access to its own address through an important pointer
called this pointer. The this pointer is an implicit parameter to all member
functions. Therefore, inside a member function, this may be used to refer to the
invoking object.

Friend functions do not have a this pointer, because friends are not members of
a class. Only member functions have a this pointer.

In C++ programming, this is a keyword that refers to the current instance of


the class. There can be 3 main usage of this keyword in C++.

It can be used to pass current object as a parameter to another


method.

It can be used to refer current class instance variable.

It can be used to declare indexers.

#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 E
mployee
e1.display();
e2.display();
return 0;
}

Output:

101 Sonoo 890000


102 Nakul 59000

Reference

When a variable is declared as a reference, it becomes an alternative


name for an existing variable. A variable can be declared as a reference by
putting ‘&’ in the declaration.
Also, we can define a reference variable as a type of variable that can act as
a reference to another variable. ‘&’ is used for signifying the address of a
variable or any memory. Variables associated with reference variables can
be accessed either by its name or by the reference variable associated with
it
Syntax:
data_type &ref = variable;
#include <iostream>
using namespace std;

int main()
{
int x = 10;

// ref is a reference to x.
int& ref = x;

// Value of x is now changed to 20


ref = 20;
cout << "x = " << x << '\n';

// Value of x is now changed to 30


x = 30;
cout << "ref = " << ref << '\n';

return 0;
}
Output:
x = 20
ref = 30

Applications of Reference in C++


There are multiple applications for references in C++, a few of them are
mentioned below:
1. Modify the passed parameters in a function
2. Avoiding a copy of large structures
3. In For Each Loop to modify all objects
4. For Each Loop to avoid the copy of objects

Dynamic memory allocation


There are times where the data to be entered is allocated at the time of
execution. For example, a list of employees increases as the new employees
are hired in the organization and similarly reduces when a person leaves the
organization. This is called managing the memory. So now, let us discuss the
concept of dynamic memory allocation.

Memory allocation

Reserving or providing space to a variable is called memory allocation. For


storing the data, memory allocation can be done in two ways

o Static allocation or compile-time allocation - Static memory


allocation means providing space for the variable. The size and data
type of the variable is known, and it remains constant throughout the
program.
o Dynamic allocation or run-time allocation - The allocation in which
memory is allocated dynamically. In this type of allocation, the exact
size of the variable is not known in advance. Pointers play a major role
in dynamic memory allocation.

Dynamically we can allocate storage while the program is in a running state,


but variables cannot be created "on the fly". Thus, there are two criteria for
dynamic memory allocation -

o A dynamic space in the memory is needed.


o Storing the address to access the variable from the memory

Similarly, we do memory de-allocation for the variables in the memory.

In C++, memory is divided into two parts -

o Stack - All the variables that are declared inside any function take
memory from the stack.
o Heap - It is unused memory in the program that is generally used for
dynamic memory allocation.

Dynamic memory allocation using the new operator

To allocate the space dynamically, the operator new is used. It means creating a
request for memory allocation on the free store. If memory is available, memory
is initialized, and the address of that space is returned to a pointer variable. The
difference between creating a normal array and allocating a block using
new normal arrays is deallocated by the compiler. Whereas the block is
created dynamically until the programmer deletes it or if the program
terminates.

If there is no space in the heap memory, the new request results in a


failure throwing an exception(std::bad_alloc) until we use nonthrow with
the new operator. Thus, the best practice is to first check for the pointer
variable.

#include <iostream>
using namespace std;
int main ()
{
// Pointer initialization to null
int* m = NULL;

// Request memory for the variable


// using new operator
m = new(nothrow) int;
if (!m)
cout<< "allocation of memory failed\n";
else
{
// Store value at allocated address
*m=29;
cout<< "Value of m: " << *m <<endl;
}
// Request block of memory
// using new operator
float *f = new float(75.25);
cout<< "Value of f: " << *f <<endl;
// Request block of memory of size
int size = 5;
int *arr = new(nothrow) int[size];
if (!arr)
cout<< "allocation of memory failed\n";
else
{
for (int i = 0; i< size; i++)
arr[i] = i+1;

cout<< "Value store in block of memory: ";


for (int i = 0; i< size; i++)
cout<<arr[i] << " ";
}

// freed the allocated memory


delete m;
delete f;
// freed the block of allocated memory
delete[] arr;

return 0;
}

Output

Value of m: 29
Value of f: 75.25
Value store in block of memory: 1 2 3 4 5

C++ Namespaces
Namespaces in C++ are used to organize too many classes so that it can be
easy to handle the application.
For accessing the class of a namespace, we need to use
namespacename::classname. We can use using keyword so that we don't
have to use complete name all the time.

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;
}

Output:

Hello First Namespace


Hello Second Namespace
Unit II
Function overloading is a feature of object-oriented programming where two
or more functions can have the same name but different parameters. When a
function name is overloaded with different jobs it is called Function
Overloading. In Function Overloading “Function” name should be the same
and the arguments should be different. Function overloading can be
considered as an example of a polymorphism feature in C++.
If multiple functions having same name but parameters of the functions
should be different is known as Function Overloading.
If we have to perform only one operation and having same name of the
functions increases the readability of the program.
Suppose you have to perform addition of the given numbers but there can be
any number of arguments, if you write the function such as a(int,int) for two
parameters, and b(int,int,int) for three parameters then it may be difficult for
you to understand the behavior of the function because its name differs.

#include <iostream>
using namespace std;

void add(int a, int b)


{
cout << "sum = " << (a + b);
}

void add(double a, double b)


{
cout << endl << "sum = " << (a + b);
}

// Driver code
int main()
{
add(10, 2);
add(5.3, 6.2);

return 0;
}
sum = 12
sum = 11.5

int myFunction(int x)
float myFunction(float x)
double myFunction(double x, double y)

int plusFuncInt(int x, int y) {


return x + y;
}

double plusFuncDouble(double x, double y) {


return x + y;
}

int main() {
int myNum1 = plusFuncInt(8, 5);
double myNum2 = plusFuncDouble(4.3, 6.26);
cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
return 0;
}

Argument matching
The compiler selects which overloaded function to invoke based on the best
match among the function declarations in the current scope to the
arguments supplied in the function call. If a suitable function is found, that
function is called. "Suitable" in this context means either:

 An exact match was found.

 A trivial conversion was performed.

 An integral promotion was performed.

 A standard conversion to the desired argument type exists.

 A user-defined conversion (either a conversion operator or a


constructor) to the desired argument type exists.
 Arguments represented by an ellipsis were found.

The compiler creates a set of candidate functions for each argument.


Candidate functions are functions in which the actual argument in that
position can be converted to the type of the formal argument.

A set of "best matching functions" is built for each argument, and the
selected function is the intersection of all the sets. If the intersection
contains more than one function, the overloading is ambiguous and
generates an error. The function that's eventually selected is always a better
match than every other function in the group for at least one argument. If
there's no clear winner, the function call generates a compiler error.

Default Arguments in Function Overloading in C++


We can define the default value in function overloading as we do it in the
main function. But the problem occurs in situations where there are multiple
matching function definitions for a function call and the compiler cannot
decide which function body to execute.
For Example, see the function overloading of:
int func(int a) { //body }
int func(int a, int b = 10) { // body }

Both of the above functions can be called using the call func(10) leading to
ambiguity issues.
C++ Program to Use Default Arguments in Function Overloading
The below example demonstrates how we can use default arguments in
function overloading in C++.
 C++

// C++ program to use default argument in function

// overloading

#include <iostream>

using namespace std;


// Function without default arguments

void display(int a, int b, int c)

cout << "Values: " << a << " " << b << " " << c << endl;

// Overloaded function with default arguments

void display(int a, int b = 10)

cout << "Values: " << a << " and " << b << endl;

int main()

display(5); // display(int a,int b=10) is called and

// default value 10 is used here because

// second arguement is missing


display(5, 20); // display(int a,int b=10) is called but

// two arguements are passed so default

// value is not used here

display(10, 15, 20); // overloaded function display(int

// a,int b,int c) is called

return 0;

Output
Values: 5 and 10
Values: 5 and 20
Values: 10 15 20

Note: When using default arguments with function overloading make sure
that any call to an overloaded function is unambiguous and compiler must be
able to select the correct function based on the function call.

Constructor Overloading in C++


We can have more than one constructor in a class with same name, as long
as each has a different list of arguments.This concept is known as
Constructor Overloading and is quite similar to function overloading.
 Overloaded constructors essentially have the same name (exact name of
the class) and different by number and type of arguments.
 A constructor is called depending upon the number and type of arguments
passed.
 While creating the object, arguments must be passed to let compiler
know, which constructor needs to be called.

#include <iostream>
using namespace std;

class construct
{

public:
float area;

// Constructor with no parameters


construct()
{
area = 0;
}

// Constructor with two parameters


construct(int a, int b)
{
area = a * b;
}

void disp()
{
cout<< area<< endl;
}
};

int main()
{
// Constructor Overloading
// with two different constructors
// of class name
construct o;
construct o2( 10, 20);

o.disp();
o2.disp();
return 1;
}

Output:
0
200

o The name of the constructor is the same as the class name


o No return type is there for constructors
o Called automatically when the object is created
o Always placed in the public scope of the class
o If a constructor is not created, the default constructor is created
automatically and initializes the data member as zero
o Declaration of constructor name is case-sensitive
o A constructor is not implicitly inherited
o

we can define how operators behave for user-defined types


like class and structures. For example,
The + operator, when used with values of type int , returns their sum.
However, when used with objects of a user-defined type, it is an error.
In this case, we can define the behavior of the + operator to work with objects
as well.
This concept of defining operators to work with objects and structure variables
is known as operator overloading.

Syntax for C++ Operator Overloading


The syntax for overloading an operator is similar to that of function with the
addition of the operator keyword followed by the operator symbol.

returnType operator symbol (arguments) {


... .. ...
}

Here,

 returnType - the return type of the function


 operator - a special keyword
 symbol - the operator we want to overload ( + , < , - , ++ , etc.)
 arguments - the arguments passed to the function
 // C++ program to overload the binary operator +
 // This program adds two complex numbers

 #include <iostream>
 using namespace std;

 class Complex {
 private:
 float real;
 float img;

 public:
 // constructor to initialize real and img to 0
 Complex() : real(0), img(0) {}
 Complex(float real, float img) : real(real), img(img){}

 // overload the + operator
 friend Complex operator + (const Complex& obj1, const
Complex& obj2) {
 Complex temp;
 temp.real = obj1.real + obj2.real;
 temp.img = obj1.img + obj2.img;
 return temp;
 }

 void display() {
 if (img < 0)
 cout << "Output Complex number: " << real << img << "i";
 else
 cout << "Output Complex number: " << real << "+" << img
<< "i";
 }
 };

 int main() {
 Complex c1(1.0f, 2.0f);
 Complex c2(1.0f, 3.0f);

 // calls the overloaded + operator
 Complex result = c1 + c2;
 result.display();

 return 0;
 }
 Run Code

 Output

 Output Complex number: 2+5i

 Here, we first created a friend function with a return type Complex .

 friend Complex operator + () {


 ...
 }

 The operator keyword followed by + indicates that we are overloading


the + operator.
 The function takes two arguments:

 friend Complex operator + (const Complex& obj1, const Complex& obj2)


{...}

You can redefine or overload most of the built-in operators available in C++.
Thus, a programmer can use operators with user-defined types as well.
Overloaded operators are functions with special names: the keyword "operator"
followed by the symbol for the operator being defined. Like any other function,
an overloaded operator has a return type and a parameter list.

Box operator+(const Box&);

declares the addition operator that can be used to add two Box objects and
returns final Box object. Most overloaded operators may be defined as ordinary
non-member functions or as class member functions. In case we define above
function as non-member function of a class then we would have to pass two
arguments for each operand as follows −

Box operator+(const Box&, const Box&);

Following is the example to show the concept of operator over loading using a
member function. Here an object is passed as an argument whose properties
will be accessed using this object, the object which will call this operator can be
accessed using this

Subscripting [] Operator
Overloading

#include <iostream>
using namespace std;
const int SIZE = 10;

class safearay {
private:
int arr[SIZE];

public:
safearay() {
register int i;
for(i = 0; i < SIZE; i++) {
arr[i] = i;
}
}

int &operator[](int i) {
if( i > SIZE ) {
cout << "Index out of bounds" <<endl;
// return first element.
return arr[0];
}

return arr[i];
}
};

int main() {
safearay A;

cout << "Value of A[2] : " << A[2] <<endl;


cout << "Value of A[5] : " << A[5]<<endl;
cout << "Value of A[12] : " << A[12]<<endl;

return 0;
}

When the above code is compiled and executed, it produces the following result

Value of A[2] : 2
Value of A[5] : 5
Index out of bounds
Value of A[12] : 0

C++ allows you to specify more than one definition for a function name or
an operator in the same scope, which is called function
overloading and operator overloading respectively.

An overloaded declaration is a declaration that is declared with the same name


as a previously declared declaration in the same scope, except that both
declarations have different arguments and obviously different definition
(implementation).

When you call an overloaded function or operator, the compiler determines


the most appropriate definition to use, by comparing the argument types you
have used to call the function or operator with the parameter types specified in
the definitions. The process of selecting the most appropriate overloaded
function or operator is called overload resolution.

Comma Operator
The purpose of comma operator is to string together several expressions. The
value of a comma-separated list of expressions is the value of the right-most
expression. Essentially, the comma's effect is to cause a sequence of operations
to be performed.

The values of the other expressions will be discarded. This means that the
expression on the right side will become the value of the entire comma-
separated expression. For example −

var = (count = 19, incr = 10, count+1);

Here first assigns count the value 19, assigns incr the value 10, then adds 1 to
count, and finally, assigns var the value of the rightmost expression, count+1,
which is 20. The parentheses are necessary because the comma operator has a
lower precedence than the assignment operator.

To see the effects of the comma operator, try running the following program −

Live Demo

#include <iostream>
using namespace std;

int main() {
int i, j;

j = 10;
i = (j++, j+100, 999+j);

cout << i;

return 0;
}

When the above code is compiled and executed, it produces the following result

1010

Conversion function
In this topic, we will discuss the conversion of one data type into another in
the C++ programming language. Type conversion is the process that
converts the predefined data type of one variable into an appropriate data
type. The main idea behind type conversion is to convert two different data
type variables into a single data type to solve mathematical and logical
expressions easily without any data loss.

For example, we are adding two numbers, where one variable is of int type
and another of float type; we need to convert or typecast the int variable into
a float to make them both float data types to add them.

Type conversion can be done in two ways in C++, one is implicit type
conversion, and the second is explicit type conversion. Those
conversions are done by the compiler itself, called the implicit type or
automatic type conversion. The conversion, which is done by the user or
requires user interferences called the explicit or user define type conversion.
Let's discuss the implicit and explicit type conversion in C++.

Implicit Type Conversion


The implicit type conversion is the type of conversion done automatically by
the compiler without any human effort. It means an implicit conversion
automatically converts one data type into another type based on some
predefined rules of the C++ compiler. Hence, it is also known as
the automatic type conversion.

1. int x = 20;
2. short int y = 5;
3. int z = x + y;

In the above example, there are two different data type variables, x, and y,
where x is an int type, and the y is of short int data type. And the resultant
variable z is also an integer type that stores x and y variables. But the C++
compiler automatically converts the lower rank data type (short int) value
into higher type (int) before resulting the sum of two numbers. Thus, it
avoids the data loss, overflow, or sign loss in implicit type conversion of C+
+.

Order of the typecast in implicit conversion


The following is the correct order of data types from lower rank to higher
rank:

1. bool -> char -> short int -> int -> unsigned int -> long int -> unsigned long int
-> long long int -> float -> double -> long double
Program to convert int to float type using implicit type conversion
Let's create a program to convert smaller rank data types into higher types
using implicit type conversion.

Program1.cpp

#include <iostream>
using namespace std;
int main ()
{
// assign the integer value
int num1 = 25;
// declare a float variable
float num2;
// convert int value into float variable using implicit conversion
num2 = num1;
cout << " The value of num1 is: " << num1 << endl;
cout << " The value of num2 is: " << num2 << endl;
return 0;
}
Output

The value of num1 is: 25


The value of num2 is: 25

You might also like