Chapter - 4 - Print
Chapter - 4 - Print
Class
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
5
Define C++ Objects:
6
Accessing the Data Members:
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.
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 main()
{
Point p1(10, 15); // Normal constructor is called here
Point p2 = p1; // Copy constructor is called here
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 (::)
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
// 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:
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;