0% found this document useful (0 votes)
20 views41 pages

unit-3.1

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 41

C++ Classes and Objects

Class: A class in C++ is the building block that leads to Object-Oriented


programming. It 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 brand but all of them will share some common properties
like all of them will have 4 wheels, Speed Limit, Mileage range etc. So here, Car
is the class and wheels, speed limits, mileage are their properties.

• A Class is a user defined data-type which has data members and member
functions.
• Data members are the data variables and member functions are the
functions used to manipulate these variables and together these data
members and member functions defines the properties and behavior of the
objects in a Class.
• In the above example of class Car, the data member will be speed
limit, mileage etc and member functions can be apply brakes, increase
speed 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.
Defining Class and Declaring Objects

A class is defined in C++ using keyword class followed by the name of class.
The body of class is defined inside the curly brackets and terminated by a
semicolon at the end.

Declaring 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;
Accessing data members and member functions: The data members and
member functions of class can be accessed using the dot(‘.’) operator with the
object. For example if the name of object is obj and you want to access the
member function with the name printName() then you will have to
write obj.printName() .

Accessing Data Members

The public data members are also accessed in the same way given however the
private data members are not allowed to be accessed directly by the object.
Accessing a data member depends solely on the access control of that data
member.
This access control is given by Access modifiers in C++. There are three access
modifiers : public, private and protected.
// C++ program to
demonstrate
// accessing of data
members

#include <bits/stdc++.h>
using namespace std;
class Geeks
{
// Access specifier
public:

// Data Members
string geekname;

// Member Functions()
void printname()
{
cout << "Geekname is:
" << geekname;
}
};

int main() {

// Declare an object of
class geeks
Geeks obj1;

// accessing data member


obj1.geekname = "Abhi";

// accessing member
function
obj1.printname();
return 0;
}
Output:
Geekname is: Abhi
Member Functions in Classes

There are 2 ways to define a member function:


• Inside class definition
• Outside class definition
To define a member function outside the class definition we have to use the
scope resolution :: operator along with class name and function name.

// C++ program to
demonstrate function
// declaration outside
class

#include
<bits/stdc++.h>
using namespace std;
class Geeks
{
public:
string geekname;
int id;

// printname is not
defined inside class
definition
void printname();

// printid is
defined inside class
definition
void printid()
{
cout << "Geek
id is: " << id;
}
};

// Definition of
printname using scope
resolution operator ::
void Geeks::printname()
{
cout << "Geekname
is: " << geekname;
}
int main() {

Geeks obj1;
obj1.geekname =
"xyz";
obj1.id=15;
// call printname()
obj1.printname();
cout << endl;

// call printid()
obj1.printid();
return 0;
}
Output:
Geekname is: xyz
Geek id is: 15
Note that all the member functions defined inside the class definition are by
default inline, but you can also make any non-class function inline by using
keyword inline with them. Inline functions are actual functions, which are
copied everywhere during compilation, like pre-processor macro, so the
overhead of function calling is reduced.
Note: Declaring a friend function is a way to give private access to a non-
member function.

Constructors in C++
Constructor in C++ is a special method that is invoked automatically at the time
of object creation. 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. Constructor is invoked at the time of object creation. It constructs the
values i.e. provides data for the object which is why it is known as constructors.
Constructor does not have a return value, hence they do not have a return type.
The prototype of Constructors is as follows:

<class-name> (list-of-parameters);
Constructors can be defined inside or outside the class declaration:-
The syntax for defining the constructor within the class:

<class-name> (list-of-parameters) {
// constructor definition }
The syntax for defining the constructor outside the class:

<class-name>: :<class-name> (list-


of-parameters){ // constructor
definition}
Example
• C++
// defining the
constructor within
the class

#include <iostream>
using namespace std;

class student {
int rno;
char name[10];
double fee;

public:
student()
{
cout <<
"Enter the RollNo:";
cin >> rno;
cout <<
"Enter the Name:";
cin >> name;
cout <<
"Enter the Fee:";
cin >> fee;
}

void display()
{
cout << endl
<< rno << "\t" <<
name << "\t" << fee;
}
};

int main()
{
student s; //
constructor gets
called automatically
when
// we
create the object of
the class
s.display();
return 0;
}
Output

Enter the RollNo:


Enter the Name:Enter the Fee:
0 6.95303e-310
Example
• C++
// defining the
constructor outside
the class

#include <iostream>
using namespace std;
class student {
int rno;
char name[50];
double fee;

public:
student();
void display();
};
student::student()
{
cout << "Enter
the RollNo:";
cin >> rno;

cout << "Enter


the Name:";
cin >> name;

cout << "Enter


the Fee:";
cin >> fee;
}

void
student::display()
{
cout << endl <<
rno << "\t" << name
<< "\t" << fee;
}

int main()
{
student s;
s.display();

return 0;
}
Output:
Enter the RollNo: 30
Enter the Name: ram
Enter the Fee: 20000
30 ram 20000
How constructors are different from a normal member function?

• C++
#include <iostream>
using namespace std;

class Line {
public:
void setLength( double len
);
double getLength( void );
Line( double len ); //This
is the constructor
private:
double length;
};
//Member function definition
including constructor
Line::Line( double len ) {
cout<<"Object is being
created , length ="<< len
<<endl;
length = len;
}
void Line::setLength( double
len ) {
length = len;
}
double Line::getLength( void )
{
return length;
}
//Main function for the
program
int main() {
Line line(10.0);
//get initially set length
cout<<"Length of line :" <<
line.getLength() << endl;
//set line length again
line.setLength(6.0);
cout<<"Length of line :" <<
line.getLength() << endl;

return 0;
}

A constructor is different from normal functions in following ways:


• Constructor has same name as the class itself
• Default Constructors don’t have input argument however, Copy and
Parameterized Constructors have input arguments
• Constructors don’t have return type
• A constructor is automatically called when an object is created.
• It must be placed in public section of class.
• If we do not specify a constructor, C++ compiler generates a default
constructor for object (expects no parameters and has an empty body).
Characteristics of the constructor:
• The name of the constructor is the same as its class name.
• Constructors are mostly declared in the public section of the class though it 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.
• Constructors can be overloaded.
• Constructor can not be declared virtual.

Types of Constructors

1. Default Constructors: Default constructor is the constructor which doesn’t


take any argument. It has no parameters. It is also called a zero-argument
constructor.

• CPP
// Cpp program to illustrate the
// concept of Constructors
#include <iostream>
using namespace std;

class construct {
public:
int a, b;

// Default Constructor
construct()
{
a = 10;
b = 20;
}
};

int main()
{
// Default constructor called
automatically
// when the object is created
construct c;
cout << "a: " << c.a << endl << "b:
" << c.b;
return 1;
}

Output

a: 10
b: 20
Note: Even if we do not define any constructor explicitly, the compiler will
automatically provide a default constructor implicitly.
• C++
// Example
#include<iostream>
using namespace std;
class student
{
int rno;
char name[50];
double fee;
public:
student() // Explicit Default
constructor
{
cout<<"Enter the RollNo:";
cin>>rno;
cout<<"Enter the Name:";
cin>>name;
cout<<"Enter the Fee:";
cin>>fee;
}

void display()
{
cout<<endl<<rno<<"\t"<<name<<"
\t"<<fee;
}
};

int main()
{
student s;
s.display();
return 0;
}
2. Parameterized Constructors: It is possible to pass arguments to constructors.
Typically, these arguments help initialize an object when it is created. To create a
parameterized constructor, simply add parameters to it the way you would to
any other function. When you define the constructor’s body, use the parameters
to initialize the object.
Note: when the parameterized constructor is defined and no default constructor is
defined explicitly, the compiler will not implicitly call the default constructor and
hence creating a simple object as
Student s;
Will flash an error
• CPP
// CPP program to
illustrate
// parameterized
constructors
#include <iostream>
using namespace std;

class Point {
private:
int x, y;

public:
// Parameterized
Constructor
Point(int x1, int
y1)
{
x = x1;
y = y1;
}

int getX() {
return x; }
int getY() {
return y; }
};
int main()
{
// Constructor
called
Point p1(10, 15);

// Access values
assigned by
constructor
cout << "p1.x = "
<< p1.getX()
<< ", p1.y =
" << p1.getY();

return 0;
}
Output

p1.x = 10, p1.y = 15


• C++
// Example

#include<iostream>
#include<string.h>
using namespace std;
class student
{
int rno;
char name[50];
double fee;

public:
student(int,char[],double);
void display();

};

student::student(int no,char n[],double


f)
{
rno=no;
strcpy(name,n);
fee=f;
}

void student::display()
{
cout<<endl<<rno<<"\t"<<name<<"\t"<
<fee;
}
int main()
{
student s(1001,"Ram",10000);
s.display();
return 0;
}
When an object is declared in a parameterized constructor, the initial values
have to be passed as arguments to the constructor function. The normal way of
object declaration may not work. The constructors can be called explicitly or
implicitly.
Example e = Example(0, 50); //
Explicit call

Example e(0, 50); //


Implicit call
• Uses of Parameterized constructor:
1. It is used to initialize the various data elements of different objects with
different values when they are created.
2. It is used to overload constructors.
• Can we have more than one constructor in a class?
Yes, It is called Constructor Overloading.

3. Copy Constructor:
A copy constructor is a member function that initializes an object using another
object of the same class.
Whenever we define one or more non-default constructors( with parameters ) for
a class, a default constructor( without parameters ) should also be explicitly
defined as the compiler will not provide a default constructor in this case.
However, it is not necessary but it’s considered to be the best practice to always
define a default constructor.
Copy constructor takes a reference to an object of the same class as an argument.

Sample(Sample &t)
{
id=t.id;
}
• C++
// Implicit copy constructor

#include<iostream>
using namespace std;

class Sample
{ int id;
public:
void init(int x)
{
id=x;
}
void display()
{
cout<<endl<<"ID="<<id;
}
};

int main()
{
Sample obj1;
obj1.init(10);
obj1.display();

Sample obj2(obj1); //or


obj2=obj1;
obj2.display();
return 0;
}
Output

ID=10
ID=10
• C++
// Example: Explicit copy
constructor

#include <iostream>
using namespace std;

class Sample
{
int id;
public:
void init(int x)
{
id=x;
}
Sample(){} //default
constructor with empty body

Sample(Sample &t) //copy


constructor
{
id=t.id;
}
void display()
{
cout<<endl<<"ID="<<id;
}
};
int main()
{
Sample obj1;
obj1.init(10);
obj1.display();

Sample obj2(obj1); //or


obj2=obj1; copy constructor
called
obj2.display();
return 0;
}
Output

ID=10
ID=10
• C++
#include<iostream>
#include<string.h>
using namespace std;
class student
{
int rno;
char name[50];
double fee;
public:
student(int,char[],double);
student(student &t) //copy
constructor
{
rno=t.rno;
strcpy(name,t.name);
fee=t.fee;
}
void display();

};
student::student(int no,char
n[],double f)
{
rno=no;
strcpy(name,n);
fee=f;
}

void student::display()
{
cout<<endl<<rno<<"\t"<<name<<"
\t"<<fee;
}

int main()
{
student s(1001,"Manjeet",10000);
s.display();

student manjeet(s); //copy


constructor called
manjeet.display();

return 0;
}
• C++
#include<iostream>
#include<string.h>
using namespace std;
class student
{
int rno;
char name[50];
double fee;
public:
student(int,char[],double);
student(student &t) //copy
constructor (member wise
initialization)
{
rno=t.rno;
strcpy(name,t.name);

}
void display();
void disp()
{
cout<<endl<<rno<<"\t"<<name;
}

};
student::student(int no, char
n[],double f)
{
rno=no;
strcpy(name,n);
fee=f;
}

void student::display()
{
cout<<endl<<rno<<"\t"<<name<<"
\t"<<fee;
}

int main()
{
student s(1001,"Manjeet",10000);
s.display();

student manjeet(s); //copy


constructor called
manjeet.disp();

return 0;
}
Destructor:
A destructor is also a special member function as a constructor. Destructor
destroys the class objects created by the constructor. Destructor has the same
name as their class name preceded by a tiled (~) 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 can-not be overloaded.
Destructor neither requires any argument nor returns any value. It is
automatically called when the object goes out of scope. Destructors release
memory space occupied by the objects created by the constructor. In destructor,
objects are destroyed in the reverse of object creation.
The syntax for defining the destructor within the class

~ <class-name>()
{
}
The syntax for defining the destructor outside the class

<class-name>: : ~ <class-name>(){}
• C++
#include <iostream>
using namespace std;

class Test {
public:
Test() { cout <<
"\n Constructor
executed"; }

~Test() { cout <<


"\n Destructor
executed"; }
};
main()
{
Test t;

return 0;
}
Output

Constructor executed
Destructor executed
• C++
#include <iostream>
using namespace std;
class Test {
public:
Test() { cout <<
"\n Constructor
executed"; }

~Test() { cout <<


"\n Destructor
executed"; }
};
main()
{
Test t, t1, t2,
t3;
return 0;
}
Output

Constructor executed
Constructor executed
Constructor executed
Constructor executed
Destructor executed
Destructor executed
Destructor executed
Destructor executed
• C++

Output

No. of Object created: 1


No. of Object created: 2
No. of Object created: 3
No. of Object created: 4
No. of Object destroyed: 4
No. of Object destroyed: 3
No. of Object destroyed: 2
No. of Object destroyed: 1
Characteristics of a destructor:-
1. Destructor is invoked automatically by the compiler when its corresponding
constructor goes out of scope and releases the memory space that is no longer
required by the program.
2. Destructor neither requires any argument nor returns any value therefore it
cannot be overloaded.
3. Destructor cannot be declared as static and const;
4. Destructor should be declared in the public section of the program.
5. Destructor is called in the reverse order of its constructor invocation.

Inline function in C++


If make a function as inline, then the
compiler replaces the function calling
location with the definition of the inline
function at compile time.
Any changes made to an inline function
will require the inline function to be
recompiled again because the compiler
would need to replace all the code with a
new code; otherwise, it will execute the
old functionality.
Syntax for an inline function:
1. inline return_type function_name(par
ameters)
2. {
3. // function code?
4. }
Let's understand the difference between
the normal function and the inline
function.

Inside the main() method, when the


function fun1() is called, the control is
transferred to the definition of the called
function. The addresses from where the
function is called and the definition of
the function are different. This control
transfer takes a lot of time and increases
the overhead.
When the inline function is encountered,
then the definition of the function is
copied to it. In this case, there is no
control transfer which saves a lot of time
and also decreases the overhead.
Let's understand through an example.

1. #include <iostream>
2. using namespace std;
3. inline int add(int a, int b)
4. {
5. return(a+b);
6. }
7. int main()
8. {
9. cout<<"Addition of 'a' and 'b' is:"<<add(2,3);
10. return 0;
11.
12. }

Once the compilation is done, the code


would be like as shown as below:

1. #include<iostream>
2. using namespace std;
3. inline int add(int a, int b)
4. {
5. return(a+b);
6. }
7. int main()
8. {
9. cout<<"Addition of 'a' and 'b' is:"
<<return(2+3);
10. return 0;
11. }
Why do we need an inline function in
C++?
The main use of the inline function in
C++ is to save memory space. Whenever
the function is called, then it takes a lot
of time to execute the tasks, such as
moving to the calling function. If the
length of the function is small, then the
substantial amount of execution time is
spent in such overheads, and sometimes
time taken required for moving to the
calling function will be greater than the
time taken required to execute that
function.
The solution to this problem is to use
macro definitions known as macros. The
preprocessor macros are widely used in
C, but the major drawback with the
macros is that these are not normal
functions which means the error
checking process will not be done during
the compilation.
C++ has provided one solution to this
problem. In the case of function calling,
the time for calling such small functions
is huge, so to overcome such a problem,
a new concept was introduced known as
an inline function. When the function is
encountered inside the main() method, it
is expanded with its definition thus
saving time.
We cannot provide the inlining to the
functions in the following circumstances:
o If a function is recursive.
o If a function contains a loop like for,
while, do-while loop.
o If a function contains static variables.
o If a function contains a switch or go
to statement
When do we require an inline function?
An inline function can be used in the
following scenarios:
o An inline function can be used when
the performance is required.
o It can be used over the macros.
o We can use the inline function outside
the class so that we can hide the
internal implementation of the
function.
Advantages of inline function
o In the inline function, we do not need
to call a function, so it does not cause
any overhead.
o It also saves the overhead of the
return statement from a function.
o It does not require any stack on which
we can push or pop the variables as it
does not perform any function
calling.
o An inline function is mainly beneficial
for the embedded systems as it yields
less code than a normal function.
Disadvantages of inline function

The following are the disadvantages of


an inline function:
o The variables that are created inside
the inline function will consume
additional registers. If the variables
increase, then the use of registers also
increases, which may increase the
overhead on register variable
resource utilization. It means that
when the function call is replaced
with an inline function body, then the
number of variables also increases,
leading to an increase in the number
of registers. This causes an overhead
on resource utilization.
o If we use many inline functions, then
the binary executable file also
becomes large.
o The use of so many inline functions
can reduce the instruction cache hit
rate, reducing the speed of
instruction fetch from the cache
memory to that of the primary
memory.
o It also increases the compile-time
overhead because whenever the
changes are made inside the inline
function, then the code needs to be
recompiled again to reflect the
changes; otherwise, it will execute the
old functionality.
o Sometimes inline functions are not
useful for many embedded systems
because, in some cases, the size of the
embedded is considered more
important than the speed.
o It can also cause thrashing due to the
increase in the size of the binary
executable file. If the thrashing occurs
in the memory, then it leads to the
degradation in the performance of
the computer.

You might also like