0% found this document useful (0 votes)
6 views21 pages

Unit-3 Notes

The document provides an overview of classes and objects in C++, focusing on access specifiers (public, private, protected), constructors, and destructors. It explains the structure of a class, how to create objects, and the importance of access modifiers in encapsulation and data integrity. Additionally, it includes examples of how to define and use member functions and the differences in access levels for class members.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views21 pages

Unit-3 Notes

The document provides an overview of classes and objects in C++, focusing on access specifiers (public, private, protected), constructors, and destructors. It explains the structure of a class, how to create objects, and the importance of access modifiers in encapsulation and data integrity. Additionally, it includes examples of how to define and use member functions and the differences in access levels for class members.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit-3

Classes and Objects: Classes and Objects in C++- Access Specifiers:


Public- Private- Protected- Constructors and Destructors in Classes.
CLASS:-
Class is a group of objects that share common properties and relationships .In
C++, a class is a new data type that contains member variables and member functions
that operates on the variables. A class is defined with the keyword class. It allows the
data to be hidden, if necessary from external use. When we defining a class, we are
creating a new abstract data type that can be treated like any other built in data type.
Generally a class specification has two parts:-
a) Class declaration
b) Class function definition
the class declaration describes the type and scope of its members. The class
function definition describes how the class functions are implemented.
Syntax:-
class class-name
{
private:
variable
declarations;
function
declaration ;
public:
variable declarations;
function declaration;
};
The members that have been declared as private can be accessed only
from with in the class. On the other hand , public members can be accessed from
outside the class also. The data hiding is the key feature of oops. The use of keywords
private is optional by default, the members of a class are private.
The variables declared inside the class are known as data members and
the functions are known as members mid the functions. Only the member functions
can have access to the private data members and private functions. However, the
public members can be accessed from the outside the class. The binding of data and
functions together into a single class type variable is referred to as encapsulation.

Syntax:-
class item
{
int
member;
public: float cost;

void getldata (int a ,float


b); d putdata (void);
voi
The class item contains two data members and two function members, the
data members are private by default while both the functions are public by declaration.
The function getdata() can be used to assign values to the member variables member
and cost, and putdata() for displaying their values . These functions provide the only
access to the data members from outside the class.
CREATING OBJECTS:
Once a class has been declared we can create variables of that
type by using the class name.
Example:
item x;
creates a variables x of type item. In C++, the class variables are known as
objects. Therefore x is called an object of type item.

item x, y ,z also
possible. class item
{

}x ,y ,z;
would create the objects x ,y ,z of type item.

ACCESSING CLASS MEMBER:


The private data of a class can be accessed only through the member
functions of that class. The main() cannot contains statements that the access number
and cost directly.
Syntax:
object [Link]-name(actual
arguments); Example:- x. getdata(100,75.5);
It assigns value 100 to number, and 75.5 to cost of the
object x by implementing the getdata() function .
similarly the statement
x. putdata ( ); //would display the values of data members.
x. number = 100 is illegal .Although x is an object of the type item to which
number belongs , the number can be accessed only through a member function and not
by the object directly.
Example:
class xyz
{

};
publi
c:
I Int
n y;
t
int z;
x
;

xyz p;
p. x =0; error . x is private
p, z=10; ok ,z is public
DEFINING MEMBER FUNCTION:
Member can be defined in two places
• Outside the class definition
• Inside the class function

OUTSIDE THE CLASS DEFlNAT1ON;

Member function that are declared inside a class have to be defined


separately outside the [Link] definition are very much like the normal functions.
An important difference between a member function and a normal
function is that a member function incorporates a [Link] label in the
header. The ‘label’ tells the compiler which class the function belongs to.

Syntax:

return type class-name::function-name(argument declaration )


{
function-body
}
The member ship label class-name :: tells the compiler that the function
function - name belongs to the class class-name . That is the scope of the function is
restricted to the class- name specified in the header line. The :: symbol is called scope
resolution operator.

Example:
void item :: getdata (int a , float b )
{
number=a;
cost=b;
}
void item :: putdata ( void)
{
cout<<”number=:”<<number<<endl;
cout<<”cost=”<<cost<<endl;
}
The member function have some special characteristics that are often used in
the program development.
• Several different classes can use the same function name. The
"membership
label" will resolve their scope, member functions can access the
private data of the class
.A non member function can't do so.
• A member function can call another member function directly, without
using the dot operator.
INSIDE THE CLASS DEF1NATION:
Another method of defining a member function is to replace the function
declaration by
the actual function definition inside the class .
Example:
class item
{
Intnumber;
float cost;
public:
void getdata (int a ,float
b); void putdata(void)
{
cout<<number<<endl; cout<<cost<<endl;
}
};
A C++ PROGRAM WITH CLASS:
# include< iostream. h>
class item
{
int
number;
public: float cost;

void getdata ( int a , float


b); void putdala ( void)
{
cout<<“number:”<<number<<endl;
cout<<”cost :”<<cost<<endl;
}
};
void item :: getdata (int a , float b)
{
number=a;
cost=b;
}
main ( )
{
item x;
cout<<”\nobjectx”<<en
dl;
x. getdata(
100,299.95); x
.putdata();
item y;
cout<<”\n object y”<<endl;
y. getdata(200,175.5);
y. putdata();
}

Output: object x
number
100

cost=299.950012
object -4
cost=175.5

Q.
Write a simple program using class in C++ to input subject mark and
prints it. ans:
class marks
{
private :
int
ml,m2;
public:
void getdata();
void
displaydata();
};
void marks: :getdata()
{
cout<<”enter 1st subject
mark:”; cin>>ml;
cout<<”enter 2nd subject
mark:”; cin>>m2;
}
void marks: :displaydata()
{
cout<<”Ist subject mark:”<<ml<<endl ;
cout<<”2nd subject mark:”<<m2;
}
void main()
{
clrscr();
marks x;
[Link]();
[Link]();

Introduction to Access Modifiers


Access modifiers in C++ specify the scope and visibility of class members; thus, they
are the main controllers of the usage of data and functions in a program. They are
instrumental in encapsulation, which is at the core of object-oriented programming and
represents the idea of binding data and the functions that operate on them into one class
while restricting access from outside. By limiting direct access to internal details, access
modifiers contribute to avoiding unintended changes, lessening the number of errors,
and being supportive of a clear, maintainable, and secure class design.
Importance of Access Modifiers in C++
Access modifiers in C++ are important in controlling the exposure of class members.
By appropriately setting access levels, developers can:
• Protect Data Integrity: Stop unauthorized or unintended access and modification
of sensitive data.
• Encapsulate Implementation Details: Conceal the internal operations of a class
and reveal only those that are necessary for the user.
• Facilitate Maintenance: Limiting access to certain code sections makes it easier to
manage and update without the risk of changing other components.
• Enhance Security: Limit access to the most important data and functions; thus,
the possibility of unintended interactions is decreased.
Default Access Specifier in C++
In C++, when you declare members inside a class or struct without specifying an access
modifier, the language assigns a default access level. This default behavior is an
important part of access control and affects encapsulation and data hiding.
• For classes:
The default access specifier is private. This means that if you do not explicitly
specify public, protected, or private, all members are only accessible within the
class itself.
• For structs and unions:
The default access specifier is public. Members are accessible from anywhere in
the program unless you specify otherwise.
Example:
class MyClass
{
int x; // here, x is private by default
};
struct MyStruct
{
int y; // y is public by default
};
In the example above:
• x in MyClass is private, so it cannot be accessed from outside the class.
• y in MyStruct is public, so it can be accessed from anywhere.
This difference is helpful in that it allows classes to hide their data (which is a good
thing in terms of encapsulation), whereas structs can still be used as mere data holders
with freely accessible members.
Note:
Unions in C++ also default their member access to public, similar to structs.

Types of C++ Access Modifiers


C++ has three fundamental access modifiers: public, private, and protected. These are
three different levels of access to class members implemented to control the access
given to other components.
Usage Examples of Access Modifiers in C++

1. Public Access Modifier in C++


In C++, access modifiers determine the visibility and accessibility of class members
(variables and functions) within and outside the class. The public access modifier is the
most permissive of all, allowing members to be accessed from any part of the program.
Characteristics of Public Members:
1. Accessible Everywhere: When a class member is declared as public, it can be
accessed from within the class itself, from derived (child) classes, and even from
external functions or objects outside the class. There are no restrictions on
accessing or modifying public members.
2. Forms the Interface of a Class: Typically, public members define the interface
of a class, allowing users of the class to interact with its data and functions.
Functions declared as public act as a bridge between the class's internal data and
the external world.
3. No Encapsulation for Public Variables: While making variables public offers
ease of access, it also violates the principle of encapsulation, as data can be
modified freely from outside the class. This can lead to unintended modifications,
causing potential security risks or logical errors in the program.
Example: Public Members in a Class
Take a simple example of Access Modifiers in C++ where the Rectangle class is
defined with public variables and methods.
Code Implementation:
#include <iostream>

class Rectangle {
public:
// Public member variables
double length;
double width;

// Public member function to calculate the area


double calculateArea() {
return length * width;
}
};

int main() {
// Creating an object of Rectangle class
Rectangle rect;

// Directly accessing and modifying public members


[Link] = 5.0;
[Link] = 3.0;

// Calling the public member function


std::cout << "Area of rectangle: " << [Link]() << std::endl;

return 0;
}

Output
Area of rectangle: 15

2. Private Access Modifier in C++


Access Modifiers in C++ control how and where the class members (variables and
functions) that are turned on by the different access modifiers can be seen and used. The
private access modifier is a tool that is put to use in the class to ensure that the members
of such a class only get accessed and changed within the class itself.
Characteristics of Private Members
1. Accessible Only Within the Class: Private members are not allowed to be
exposed directly outside the class. Only member functions of the same class have
the right to modify private variables.
2. Ensures Data Hiding and Encapsulation: One of the ways private members
bolster the data-hiding mechanisms is by not letting one directly modify the
internal state of an object through them. This is indeed a way of introducing and
enforcing data integrity as well as preventing the occurrence of unintended
changes or the instantiation of the improper values.
3. Requires Public Methods for Interaction: The benefit of having private
members is that you are sure that no one other than the class holder will tamper
with these members, thus ensuring security and data consistency. To still be able
to interact with these private members, we have to write public methods, which
are essentially getters and setters that expose these members in a controlled way.
Example: Private Members in a Class
#include <iostream>

class Rectangle {
private:
double length;
double width;

public:
// Setter method to assign values (controlled access)
void setDimensions(double l, double w) {
if (l > 0 && w > 0) {
length = l;
width = w;
} else {
std::cout << "Invalid dimensions! Length and width must be positive." <<
std::endl;
}
}

// Getter method to calculate the area


double calculateArea() {
return length * width;
}
};

int main() {
Rectangle rect;

// Using setter to assign values


[Link](5.0, 3.0);

// Calling a public function to get the area


std::cout << "Area of rectangle: " << [Link]() << std::endl;

return 0;
}
Output
Area of rectangle: 15

What Happens if We Try to Access Private Members Directly?


If we attempt to modify length or width directly, like this:
Rectangle rect;
[Link] = 5.0; // Compilation Error: 'length' is private
[Link] = 3.0; // Compilation Error: 'width' is private

3. Protected Access Modifier in C++


In C++, access modifiers determine the visibility and accessibility of class members
(variables and functions). Private and the protected access modifier are comparable,
however there is a crucial difference:
• Protected members cannot be accessed from outside the class (just like private
members).
• However, they can be accessed within derived (child) classes.
This feature is especially helpful in inheritance, where a base class may want to give
access to its members for derived classes but prohibiting direct access from outside the
class hierarchy.
Characteristics of Protected Members
1. Not Accessible Outside the Class: Similar to private members, protected
members cannot be accessed directly using an object of the class.
2. Accessible in Derived Classes: Unlike private members, protected members can
be inherited and used by derived (child) classes. This allows controlled access
while still maintaining encapsulation.
3. Useful in Inheritance Hierarchies: In case of designing a class that is going to
be inherited, protected members give the possibility to the derived classes to use
and change the base class data and at the same time, the data remains inaccessible
to the outside.
Example: Using Protected Members in an Inheritance Hierarchy
#include <iostream>

// Base class
class Shape {
protected:
double area; // Protected member
};

// Derived class inheriting from Shape


class Rectangle : public Shape {
private:
double length;
double width;

public:
// Public method to set dimensions and calculate area
void setDimensions(double l, double w) {
length = l;
width = w;
area = length * width; // Accessing protected member of base class
}
// Public method to display the area
void displayArea() {
std::cout << "Area of rectangle: " << area << std::endl;
}
};

int main() {
Rectangle rect;

// Setting dimensions
[Link](5.0, 3.0);

// Displaying the area


[Link]();

return 0;
}

Output
Area of rectangle: 15

What Happens If We Try to Access Protected Members Outside the Class?


If we try to access area directly from main(), like this:
int main() {
Rectangle rect;
[Link] = 20; // Compilation Error: 'area' is protected
return 0;
}
Constructors
A constructor is a specially defined method in a C++ class that is automatically called when an
instance of that class is created. It is typically used for tasks such as initializing class attributes in a
new object. Like with functions, a constructor can take arguments that can aid in the initialization.
The arguments are passed to the constructor method when a new object is created.

Characteristics of Constructors in C++


• A constructor has the same name as its class.
• It doesn’t return values, which means it doesn’t have a return type.
• It is mostly declared in the public section of a class. However, it can be declared in the private
section, too.
• We can’t declare a virtual constructor.
• The address of a constructor can’t be referenced to.
• It is invoked automatically when an object of a class is created.
• Overloaded constructors are possible.
• Inheritance in constructors is not allowed.

Syntax
A constructor method is defined within a class by using the ClassName followed by parentheses. It
does not have a return type.
class ClassName {
public:
ClassName() {
// Constructor code
}
};

Types of Constructors in C++


Based on the situation in which it is used, a constructor can be divided into four types:
Default Constructor: They have no parameters and create an object with default values.
Parameterized Constructor: They accept parameters and create objects with specific initial
values.
Copy Constructor: They take a reference to another object of the same class. And are used to
create a copy of an object.
Basic Constructor
A basic constructor, also known as a default constructor, is a special type of constructor in C++
that takes no parameters.
The compiler will automatically provide a default constructor if there is no constructor explicitly
defined for a class.
This constructor is used for initializing an object when no specific values are needed, and it also
initializes member variables to default values.
class MyClass {
public:
// Define a basic constructor
MyClass() {
std::cout << "The constructor was executed!";
}
};

int main() {
MyClass myObject; // This calls the constructor
return 0;
}

Copy to clipboard
The result of the following code:
The constructor was executed!

Parameterized Constructor
A parameterized constructor is one that accepts arguments, allowing initial values to be set for an
object’s attributes at the time of creation. This constructor is useful for initializing objects with
custom data or values that differ between instances.
class Circle {
public:
int X;
int Y;
int radius;

Circle (int a, int b, int c) {


X = a;
Y = b;
radius = c;
}
};

int main() {
// Call the constructor using arguments
Circle myCircle1(5,5,10);
Circle myCircle2(0,0,5);
// Print out the attribute values set for each object

std::cout << "X=" << myCircle1.X << ", Y=" << myCircle1.Y << ", radius=" <<
[Link] << "\n";
// Output: X=5, Y=5, radius=10

std::cout << "X=" << myCircle2.X << ", Y=" << myCircle2.Y << ", radius=" <<
[Link] << "\n";
// Output: X=0, Y=0, radius=5

return 0;
}

Copy to clipboard
The result of the following code:
X=5, Y=5, radius=10
X=0, Y=0, radius=5

Copy Constructor
A C++ copy constructor is a member function that initializes an object using another object of the
same class. When we specify one or more non-default constructors for a class, we must also
include a default constructor because the compiler doesn’t provide one in such a situation. Hence,
it is best to always declare a default constructor, even if it is not required. The copy constructor
needs a reference to the object belonging to the same class.
Similar to a default constructor, the compiler in C++ also provides an implicit copy constructor if it
is not present explicitly. In the default constructor, the presence of an explicit constructor leads to
the deletion of the implicit default constructor. However, the compiler always creates the implicit
copy constructor if no explicit copy or explicit move constructor is present.
Syntax of C++ Copy Constructor:
ClassName (ClassName &obj)
{
// body_containing_logic
}
Uses
• Used for copying objects properly to manage resources like dynamic memory.
• To create new objects as a copy of existing objects.
Pros
• Avoids resource leaks and undefined behavior from shallow copying.
• Ensures that there is a deep copy of objects while managing dynamic resources.
Cons
• Demands careful implementation so all resources are copied correctly.
• When the copied object is large, it can be expensive in terms of performance.
Difference Between different types of Constructors in C++

Default Parameterized Copy


Parameter Move Constructor
Constructor Constructor Constructor

It initializes an
It takes object using
This constructor arguments to another object It moves resources
Definition is called without initialize an of the same from a temporary
any arguments. object with class and object to a new object.
specific values. performs a deep
copy.

MyClass(const
MyClass(MyClass&&
Syntax MyClass(); MyClass(int a); MyClass&
other) noexcept;
other);

Create an object Create an object Create a deep Transfer resources


Purpose with default with specific copy of an from a temporary
values. initial values. existing object. object to a new object.

Invoked
Invoked when an Invoked when Invoked when an
automatically
object is created an object is object is initialized
Invocation when an object is
with specific copied from using an rvalue
created with
initial values. another object. reference.
default values.
Destructors

In C++, a destructor is a special member function of a class that runs when an object of that class
goes out of scope or is explicitly deleted. Imagine you have a paper airplane, and when you're
done playing with it, you need to recycle the paper. A destructor helps with that recycling
process in programming.
Destructors are vital because they ensure that resources, like memory or files, are properly
released. This prevents memory leaks.
Destructor Syntax
A destructor has the same name as the class but is preceded by a tilde (~). It doesn't take any
arguments and doesn't return any value. Additionally, a class can only have one destructor, you
can't overload it.
Here's a simple example:
class MyClass {
public:
// Constructor
MyClass() {
// Constructor code
}

// Destructor
~MyClass() {
// Destructor code
}
};
This class MyClass has a constructor (to set up the object) and a destructor (to clean up the
object). If you don't define a destructor, the compiler provides a default one. However, it's a good
practice always to declare your own destructor if your class manages resources like dynamic
memory, file handles, or network connections. This ensures that resources are correctly and
explicitly released.
You can also define the destructor outside the class, just like with other methods
// Destructor implementation outside the class
MyClass::~MyClass() {
// Destructor code
}
Destructors in Action
#include <iostream>

class MyClass {
public:
MyClass() : data(nullptr) {
std::cout << "Constructor called!" << std::endl;
}
~MyClass() {
std::cout << "Destructor called!" << std::endl;
}

private:
int* data;
};

int main() {
MyClass obj; // Constructor called here
return 0; // Destructor called here
}
Here's what's happening:
• When obj is created, the constructor runs and prints "Constructor called!".
• When obj goes out of scope (at the end of main), the destructor runs and prints
"Destructor called!".
Key Points to Remember
• Automatic Calling: Destructors are called automatically when an object goes out of
scope or is deleted.
• Only One Destructor: A class can have only one destructor.
• Default Destructor: If you don't define a destructor, the compiler provides a default one.
• Write Outside the Class: You can write the body of the destructor outside of the class
definition.
• No Throwing Exceptions: A destructor should not throw exceptions because it might
not be safely caught if an exception is thrown during the destruction process. This is
because destructors can be invoked during the stack unwinding process of another
exception, leading to a call to std::terminate.

Constructor vs Destructor
Constructor Destructor
Initializing class variables and objects is done in Destructors are used to get rid of or
the function using constructor dereference class objects.
It may or may not take arguments It does not take arguments
It is called when the object is created It is called when the object is
destroyed
Constructor can be overloaded Destructor cannot be overloaded
Name is the same as class name Name is same as class name preceded
by tilde operator
Multiple constructors can exist Only single destructor can exist
They are called first from parent and then to They are first called from first child
child and then to parent

You might also like