0% found this document useful (0 votes)
21 views46 pages

Chapter - 4 - Print

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

Chapter - 4 - Print

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

CHAPTER -4

Class

After covering this unit you will understand…


• Classes
– Defining, member functions
– Public, protected and private members

1
class
• Class is a collection of data member and member function.
Objects are also called instance of the class.
• A class is a data type defined by the programmer, consisting
of variables and functions.
• Each object contains all members(variables and functions)
declared in the class.
• We can access any data member or member function
from object of that class .
• A class is the collection of related data and function under a
single name.
• A C++ program can have any number of classes. When
related data and functions are kept under a class, it helps to
visualize the complex problem efficiently and effectively. 2
A class specification has two parts :
1) Class declaration
2) Class Function Definitions

A Class is a blueprint for objects


When a class is defined, No Memory Is Allocated. You can imagine
like a data type.
int var;
The above code specifies var is a variable of type integer;
int is used for specifying variable var is of integer type.
Similarly, class are also just the specification for objects
and object bears the property of that class. 3
Cont’d…
A class definition starts with the
keyword class followed by the class name; and the
class body, enclosed by a pair of curly braces. A
class definition must be followed either by a
semicolon or a list of declarations
class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box }; 4
class
• The keyword public determines the access
attributes of the members of the class that follow it.
• A public member can be accessed from outside the
class anywhere within the scope of the class object.
You can also specify the members of a class
as private or protected .

5
Define C++ Objects:

• A class provides the blueprints for objects, so


basically an object is created from a class.
• We declare objects of a class with exactly the same
sort of declaration that we declare variables of basic
types. Following statements declare two objects of
class Box:
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box

6
Accessing the Data Members:

The public data members of objects of a class can be


accessed using the direct member access operator
(.).

7
#include <iostream.h>
Cont’d…
class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main( )
{ Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here // box 1 specification Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0; // box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0; // volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl; // volume of box 2
8
volume = Box2.height * Box2.length * Box2.breadth;
Access Specifiers
• C++ provides the key words private and public which you may use
in class declarations.
• These key words are known as access specifiers because they
specify how class members may be accessed. The following is the
general format of a class declaration that uses the private and
public access specifiers.
class ClassName
{
private:
// Declarations of private
// members appear here.
public:
// Declarations of public
// members appear here. 9
Cont’d…

10
Cont’d…
• The keyword class specifies user defined data type class name
• The body of a class is enclosed within braces and is terminated by a
semicolon
• The class body contains the declaration of variables and functions
• The class body has three access specifiers ( visibility labels) viz.,
private , public and protected
• Specifying private visibility label is optional. By default the members
will be treated as private if a visibility label is not mentioned
• The members that have been declared as private, can be accessed
only from within the class
• The members that have been declared as protected can be
accessed from within the class, and the members of the inherited
classes.
• The members that have been declared as public can be accessed
from outside the class also 11
Data Abstraction
• The binding of data and functions together into a single
entity is referred to as encapsulation.
• The members and functions declared under private are not
accessible by members outside the class, this is referred to
as data hiding.
• Allowing only selected access of components to objects and
to members of other classes is called as Data Abstraction.
Or rather Data abstraction is achieved through data hiding.

12
The public Members
#include <iostream>
using namespace std;
class Line {
public:
double length;
void setLength( double len );
double getLength( void );
};
double Line::getLength(void) {
return length ;
}
void Line::setLength( double len) {
length = len;
}
int main() {
Line line;
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
// set line length without member function
line.length = 10.0; // OK: because length is public
cout << "Length of line : " << line.length <<endl;
return 0;
}

13
The private Members
#include <iostream>
using namespace std;
class Box {
public:
double length;
void setWidth( double wid );
double getWidth( void );
private:
double width;
};
double Box::getWidth(void) {
return width ;
}
void Box::setWidth( double wid ) {
width = wid;
}
// Main function for the program
int main() {
Box box;
// set box length without member function
box.length = 10.0; // OK: because length is public
cout << "Length of box : " << box.length <<endl;
// set box width without member function
// box.width = 10.0; // Error: because width is private
box.setWidth(10.0); // Use member function to set it.
cout << "Width of box : " << box.getWidth() <<endl;
return 0;
} 14
The protected Members
#include <iostream>
using namespace std;
class Box {
protected:
double width;
};
class SmallBox:Box { // SmallBox is the derived class.
public:
void setSmallWidth( double wid );
double getSmallWidth( void );
};
// Member functions of child class
double SmallBox::getSmallWidth(void) {
return width ;
}
void SmallBox::setSmallWidth( double wid ) {
width = wid;
}
// Main function for the program
int main() {
SmallBox box;
// set box width using member function
box.setSmallWidth(5.0);
cout << "Width of box : "<< box.getSmallWidth() << endl;
return 0;
}
15
Data Members and Member Functions
• Class comprises of members. Members are further
classified as Data Members and Member functions.
Data members are the data variables that represent
the features or properties of a class.
• Member functions are the functions that perform
specific tasks in a class.
• Member functions are called as methods, and data
members are also called as attributes.

16
Cont’d…

17
Accessors and Mutators
• A member function that gets a value from a class’s
member variable but does not change it is known as an
accessor.
• A member function that stores a value in member
variable or changes(mutates) the value of member variable
in some other way is known as a mutator.
• In the Rectangle class, the member functions getLength
and getWidth are accessors, and the member functions
setLength and setWidth are mutators.
• Some programmers refer to mutators as setter functions
because they set the value of an attribute, and accessors
as getter functions because they get the value of an
attribute.
18
Cont’d…
#include <iostream>
class Rectangle
{
int width, height;
public:
void set values(int,int); //mutator
int area ()
{
return width*height;}
};
void Rectangle::set_values (int x, int y) {
width = x; height = y; }
int main ()
{
Rectangle rect, rectb;
rect.set_values (3,4);
rectb.set_values (5,6);
cout << "rect area: " << rect.area() << endl;
19
cout << "rectb area: " << rectb.area() << endl;
Creating Objects
• declaration statement student stud; This statement may be
read as stud is an instance or object of the class student.
Syntax for object declaration.

• Once a class has been declared, variables of that type can be


declared. ‘stud’ is a variable of type student ,student is a data
type of class .
• In C++ the class variables are known as objects. The
declaration of an object is similar to that of a variable of any
basic type.
• Objects can also be created by placing their names
immediately after the closing brace of the class declaration. 20
Cont’d…
• Class objects must be defined after the class is
declared.
Rectangle box;
• ClassName is the name of a class and objectName is
the name we are giving the object.
• Defining a class object is called the instantiation of a
class. In this statement, box is an instance of the
Rectangle class.

21
Accessing an Object’s Members
• The members of a class are accessed using the dot
operator.
• The dot operator is used to connect the object and
the member function.
• For example, the call statement to the function
execute() of the class student may be given as:

box.setWidth(12.7); 22
constructor
• A constructor is a member function that is
automatically called when an object of that class is
declared.
• A constructor is used to initialize the values of some
or all member variables and to do any other sort of
initialization that may be needed.
• A constructor is a member function of a class that has
the same name as the class.
• A constructor is called automatically when an object
of the class is declared. Constructors are used to
initialize objects.
• A constructor must have the same name as the class23
CONSTRUCTOR DEFINITIONS
You define a constructor the same way that you
define any other member function, except for two
points:
1. A constructor must have the same name as the
class. For example, if the class is named
BankAccount , then any constructor for this class
must be named BankAccount
2. A constructor definition cannot return a value.
Moreover, no type, not even Void can be given at
the start of the function declaration or in the
function header.
Constructors can be overloaded 24
Cont’d…
class rectangle { // A simple class
int height;
int width;
public:
rectangle(void); // with a constuctor,
~rectangle(void); // and a destructor
};
rectangle::rectangle(void) // constuctor
{
height = 6; width = 6;
} 25
#include <iostream.h>
Cont’d… {
// A simple class declaration // destroy all the object an return the resources to the system
class rectangle height = 0;
{ width = 0;
// private access by default, access only through the method or interface }
int height; // normal structure - compare with class usage
int width; struct pole
// public {
public: int length;
// constructor, initial object construction, allocating storage, initial value etc. int depth;
rectangle(void); };
// methods, access something, do something // comes the main()
int area(void); int main(void)
void initialize(int, int); {
// destructor, destroy all the object, return resources such as memory etc. to the system // class object instantiations
~rectangle(void); rectangle wall, square;
}; // normal struct
// class implementation pole lamp_pole;
// constructor implementation
rectangle::rectangle(void) cout<<"Check the size of rectangle = "<<sizeof(rectangle)<<" bytes"<<endl;
{ cout<<"Check the size of pole = "<<sizeof(pole)<<" bytes"<<endl<<endl;
// give initial values cout<<"Using class instead of struct, using DEFAULT VALUE"<<endl;
height = 6; cout<<"supplied by constructor, access through area() method"<<endl;
width = 6; cout<<"----------------------------------------------------"<<endl<<endl;
} cout<<"Area of the wall, wall.area() = "<<wall.area()<<endl;
int rectangle::area(void) cout<<"Area of the square, square.area() = "<<square.area()<<endl<<endl;
{ // we can override the constructor values
// just return the area wall.initialize(12, 10);
return (height * width); square.initialize(8,8);
} cout<<"Using class instead of struct, USING ASSIGNED VALUE, access through area()
void rectangle::initialize(int initial_height, int initial_width) method"<<endl;
{ cout<<"---------------------------------------------------------------------------------"<<endl;
// give initial values cout<<"Area of the wall, wall.area() = "<<wall.area()<<endl;
height = initial_height; cout<<"Area of the square, square.area()= "<<square.area()<<endl<<endl;
width = initial_width; lamp_pole.length = 50;
} lamp_pole.depth = 6;
// destructor implementation cout<<"Just a comparison to the class, the following is a struct"<<endl; 26
rectangle::~rectangle(void) cout<<"The length of the lamp pole is = "<<lamp_pole.length*lamp_pole.depth<<endl<<endl;
Types of constructors
1. Default Constructor:-
• Default Constructor is also called as Empty
Constructor which has no arguments and It is
Automatically called when we creates the object of
class but Remember name of Constructor is same
as name of class and Constructor never declared
with the help of Return Type.
• Means we cant Declare a Constructor with the
help of void Return Type. , if we never Pass or
Declare any Arguments then this called as the
default Constructors.
27
Cont’d…
2. Parameterized Constructor :-
• This is Another type Constructor which has some
Arguments and same name as class name but it
uses some Arguments So For this We have to
create object of Class by passing some Arguments
at the time of creating object with the name of
class.
• When we pass some Arguments to the Constructor
then this will automatically pass the Arguments to
the Constructor and the values will retrieve by the
Respective Data Members of the Class.
28
Cont’d…
#include<iostream.h> cout<<"Pages:"<<pages<<endl<<endl;}
#include<conio.h> };
#include<string.h> Int main()
class Book{ {
private: Book b1(25, "C++");
int pages; Book b2(b1);
char title[3]; Book b3= b1;
public: cout<<"detail of b1:"<<endl;
Book(int q, char w[3]) b1.show();
{ cout<<"detail of b2:"<<endl;
pages= q; b2.show();
for(int i=0 ; i<3 ; i++) cout<<"detail of b3:"<<endl;
{ b3.show();
title[i]= w[i];} getch();
} }
void show()
{
29
cout<<"Title:"<<title<<endl;
Cont’d…
3. Copy Constructor:-
• In this Constructor we pass the object of class into
the Another Object of Same Class.
• As name Suggests you Copy, means Copy the values
of one Object into the another Object of Class .
• This is used for Copying the values of class object
into an another object of class So we call them as
Copy Constructor and For Copying the values We
have to pass the name of object whose values we
wants to Copying and When we are using or passing
an Object to a Constructor then we must have to
use the & Ampersand or Address Operator. 30
#include<iostream>
Cont’d…
using namespace std;

class Point
{
private:
int x, y;
public:
Point(int x1, int y1) { x = x1; y = y1; }

// Copy constructor
Point(const Point &p1) {x = p1.x; y = p1.y; }

int getX() { return x; }


int getY() { return y; }
};

int main()
{
Point p1(10, 15); // Normal constructor is called here
Point p2 = p1; // Copy constructor is called here

// Let us access values assigned by constructors


cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();

return 0;
} 31
DESTRUCTOR
• The destructor of a class is a member function of a
class that is called automatically when an object of
the class goes out of scope.
• Among other things, this means that if an object of
the class type is a local variable for a function, then
the destructor is automatically called as the last
action before the function call ends.
• Destructors are used to eliminate any dynamically
allocated variables that have been created by the
object so that the memory occupied by these
dynamic variables is returned to the free store
manager for reuse. 32
Cont’d…
• Destructors may perform other clean-up tasks as
well. The name of a destructor must consist of the
tilde symbol, ~, followed by the name of the class.

33
Cont’d…
#include <iostream>
using namespace std;
class ABC
{
public:
ABC () //constructor defined
{
cout << "Hey look I am in constructor" << endl;
}
~ABC() //destructor defined
{
cout << "Hey look I am in destructor" << endl;
}
};
int main()
{
ABC cc1; //constructor is called
cout << "function main is terminating...." << endl;
/*....object cc1 goes out of scope ,now destructor is being called...*/ 34
Constructors VS destructors
• For global objects, an object’s constructor is called once,
when the program first begins execution.
• For local objects, the constructor is called each time the
declaration statement is executed.
• Local objects are destroyed when they go out of scope.
• Global objects are destroyed when the program ends.
• Constructors and destructors are typically declared as public.
• That is why the compiler can call them when an object of a
class is declared anywhere in the program.
• If the constructor or destructor function is declared as
private then no object of that class can be created outside of
that class.
• A class can have multiple constructors.
• It is possible to pass arguments to a constructor function.
• Destructor functions cannot have parameters. 35
Scope Resolution Operator (::)

• The scope resolution operator : : is a special


operator that allows access to a global variable that is hidden by a local
variable with the same name.

• is used to define a function outside a class or when


we want to use a global variable but also has a local
variable with same name
• To understand the concept of scope resolution
operator, consider this example.

36
Cont’d…
#include<iostream.h>
int x = 5;
int main ()
{
int x = 3;
cout<<”The local variable of outer block is: “<<x;
cout<<”\nThe global variable is: “<<::x;
{
int x = 10;
cout <<”The local variable of inner block is: “<<x;
cout <<”\n The global variable is: “<<::x;
}
return 0; 37
Cont’d…
#include<iostream.h>
int n=12; //global variable
int main()
{
int n=13; //local variable
cout<<::n<<endl; //print global variable:12
cout<<n<<endl; //print the local variable:13
}

38
Static members of class

• We can define class members static


using static keyword. When we declare a member of
a class as static it means no matter how many objects
of the class are created, there is only one copy of the
static member.
• A static member is shared by all objects of the class.
All static data is initialized to zero when the first
object is created, if no other initialization is present.
• We can't put it in the class definition but it can be
initialized outside the class as done in the following
example by redeclaring the static variable, using the
scope resolution operator :: to identify which class it
39
#include <iostream>
Cont’d…
using namespace std;
class Box {
public:
static int objectCount;

// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
// Increase every time object is created
objectCount++;
}
double Volume() {
return length * breadth * height;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
// Initialize static member of class Box
int Box::objectCount = 0;
int main(void) {
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
// Print total number of objects.
cout << "Total objects: " << Box::objectCount << endl;
return 0;} 40
Static Function Members:

• By declaring a function member as static, you make it


independent of any particular object of the class. A static
member function can be called even if no objects of the
class exist and the static functions are accessed using
only the class name and the scope resolution operator ::.
• A static member function can only access static data
member, other static member functions and any other
functions from outside the class.
• Static member functions have a class scope and they do
not have access to the this pointer of the class. You
could use a static member function to determine
whether some objects of the class have been created or
not. 41
Cont’d…
#include <iostream>
using namespace std;
class Box {
public:
static int objectCount;
// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
// Increase every time object is created
objectCount++;
}
double Volume() {
return length * breadth * height;
}
static int getCount() {
return objectCount;
}

private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
// Initialize static member of class Box
int Box::objectCount = 0;

int main(void) {
// Print total number of objects before creating object.
cout << "Inital Stage Count: " << Box::getCount() << endl;

Box Box1(3.3, 1.2, 1.5); // Declare box1 42


Box Box2(8.5, 6.0, 2.0); // Declare box2
Friend functions

• In principle, private and protected members of a


class cannot be accessed from outside the same
class in which they are declared. However, this rule
does not apply to "friends".
• Friends are functions or classes declared with
the friend keyword.
• A non-member function can access the private and
protected members of a class if it is declared
a friend of that class. That is done by including a
declaration of this external function within the
class, and preceding it with the keyword friend:
43
// friend functions
Cont’d…
#include <iostream>
class Rectangle {
int width, height;
public:
Rectangle() {}
Rectangle (int x, int y) :
width(x), height(y) {}
int area() {return width * height;}
friend Rectangle duplicate (const Rectangle&);
};
Rectangle duplicate (const Rectangle& param) {
Rectangle res; res.width = param.width*2;
res.height = param.height*2;
return res; }
int main () {
Rectangle foo;
Rectangle bar (2,3); foo = duplicate (bar);
44
cout << foo.area() << '\n';
Friend classes in C++:-

• These are the special type of classes whose all of the


member functions are allowed to access the private and
protected data members of a particular class is known as
friend class.
• Normally private and protected members could not be
accessed from outside the class but in some situations
the program has to access them in order to produce the
desired results.
• In such situations the friend classes are used, the use of
friend classes allows a class to access these members of
another class.
• The syntax of declaring a friend class is not very tough,
simply if a class is declared in another class with a friend
45
Cont’d…
#include<iostream.h> void showA(A obj)
#include<conio.h> {
class A cout<<"The value of a: "<<obj.a<<endl;
{ }
private: void showB(A obj)
int a,b; {
public: cout<<"The value of b:"<<obj.b<<endl;
A() }
{ };
a=10; int main()
b=20; {
} A x;
friend class B; B y;
}; y.showA(x);
class B y.showB(x);
{ getch();
public: } 46

You might also like