Unix 6 and 7_objects and Classes_ Constructors (1)
Unix 6 and 7_objects and Classes_ Constructors (1)
Learning outcomes
Declare a class
At the heart of object-oriented programming is the object. An object is an entity -an instance of a data type
-that has structure and state. Each object defines operations that may access or manipulate that state.
Class
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 class is like a blueprint for an object.
Classes are fundamental building blocks of object-oriented programs. A class binds data and functions
together. The data and functions of a class are its members.
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, e.g., 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 (attributes).
A Class is a user defined data-type which has data members and member functions.
Page 1 of 29
Data members are the data variables
Member functions are the functions used to manipulate these variables. These data members and
member functions together define 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
Derived Class: A class that is created from an existing class. It inherits all members and member
functions of a base class. The derived class can have more functionality with respect to the Base
class and can easily access the Base class. A Derived class is also called a child class or subclass.
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.
Specifying the data members and member functions of a class is known as declaring a class.
The class definition begins with class keyword followed by the name of the class. The name of a class is an
identifier and it is not supposed to be a reserved word. The body of a class is enclosed within the opening
curly brace ({) and closing curly brace (}). The closing curly brace is terminated by a semi-colon (;). The
body of a class consists of data members and member functions.
Page 2 of 29
Class class_name
private:
data_type number1;
data_type number2;
………….
data_type numbern;
public:
method function1;
method function2;
……………………..
};
Page 3 of 29
Example :
Class Rectangle{
private:
int length;
int width;
public:
void print_dimension(void);
};
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:
Page 4 of 29
ClassName ObjectName;
A class in C++ consists of its members. These members can be either data or functions. The functions are
called member functions. Each instance of a class is an object. Each object contains the data components
specified in the class (unless the data components are static). A member function is used to act on an object.
Member functions are also called methods.
The data members and member functions details are controlled using private, public
and protected keywords. Private, public and protected keywords are also referred to as
access specifiers/modifiers and are always followed by a colon (:).
The private section of a class has data members and member functions that are
available only within the class (except by friend functions).
The public section makes the data members and member functions within it to
be available to all class members and to the other classes’ members and
applications.
The protected section has data members and member functions that are
available to the class itself and any other derived class.
The beginning of each section is marked by keywords private: public: and protected:
NB: By default data members and member functions are private.
Normally the data members are put in the private section of a class and the member
functions are put in the public section.
Page 5 of 29
a) Definition of a member function outside a class definition
The member functions declared within a class can be defined outside a class.
The definitions of these functions are just the same as definition of the normal functions
(functions that are not members of a class). But unlike normal functions, member
functions defined outside a class definition are qualified with the name of the class that
they belong to. The name of the class and the member function are separated using the
scope resolution operator (: :).
For instance, consider the print_dimension function declared in the Rectangle class
above. It may be defined as follows:
{
cout<< “The Length is:”<<length <<”cm\n” <<”The width is :” <<width <<”cm\n”
<<endl;
Member functions can be defined within a class definition. Still consider the print_dimension()
function declared in the class Rectangle above. This function can be defined in the class as shown
below.
class Rectangle
{
private:
int length;
int width;
public:
Page 6 of 29
void funt()
)
{
cout<< “The Length is:”<length << “cm\n” << “The width is :” <<width < “cm\n”<<endl;
};
a) Form 1
class-name variable-name;
e.g.
Rectangle rect1;
b) Form 2
class-name variable-name(arguments);
e.g.
Page 7 of 29
The above two statements create class variables rect1 and rect2 of type Rectangle. A class variable is an
object. In that case rect1and rect2 are objects of type Rectangle
/* ————————————————————————————————
Rectangle.cpp
—————————————————————————————————-
*/
#include<iostream>
using namespace std;
class Rectangle{
private:
int length;
int width;
public:
Page 8 of 29
};
int main(void)
Rectangle rect1(5,3);
rect1.print_dimension();
return 0;
}
/* ————————————————————————————————
—–
—————————————————————————————————-
*/
length=l;
width=w;
}
/* ————————————————————————————————
—–
—————————————————————————————————-
*/
Page 9 of 29
cout<<”The Length is: “<<length <<”cm\n” <<”The width is : “<<width <<”cm\n”
<<endl;
If you compile and execute this program, the output is The Length is: 5cm The width is : 3cm
Example
To access public members of a class, we use the (.)dot operator.
These are members marked with public access modifier.
#include <iostream>
using namespace std;
class Phone {
public:
double cost;
int slots;
};
int main() {
Phone Y6;
Phone Y7;
Y6.cost = 100.0;
Y6.slots = 2;
Y7.cost = 200.0;
Y7.slots = 2;
Example
Write a C++ program to find sum of two integer using class and object.
#include <iostream>
using namespace std;
//class definition
class Numbers
{
private:
int a; int b;
public:
//member functions declaration
void readNumbers(void);
void printNumbers(void);
int calAddition(void);
};
void Numbers::readNumbers(void)
Page 11 of 29
{
int Numbers::calAddition(void)
return (a+b);
//main program
int main()
{
Numbers num; //declaring object
int add; //variable to store addition
//take input
num.readNumbers();
//find addition
add=num.calAddition();
//print numbers
num.printNumbers();
//display addition
Page 12 of 29
cout<<"The sum is "<<add<<endl;
return 0;
}
Example 2
#include <iostream>
class Box {
public:
};
int main() {
// box 1 specification
Box1.height = 5.0;
Page 13 of 29
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 of box 2
return 0;
Page 14 of 29
#include <bits/stdc++.h>
class ClassName
// Data Members
string Myname;
// Member Functions()
void printname()
};
int main() {
names obj1;
Page 15 of 29
obj1.printname();
return 0;
Example 3
Write a C++ program to find sum of two integer using class and object.
#include <iostream>
private:
int a; int b;
public:
void printNumbers(void);
int calAddition(void);
};
Page 16 of 29
//member function definitions
void Numbers::readNumbers(void)
void Numbers::printNumbers(void)
int Numbers::calAddition(void)
return (a+b);
//main function
int main()
//declaring object
Numbers num;
Page 17 of 29
int add; //variable to store addition
//take input
num.readNumbers();
//find addition
add=num.calAddition();
//print numbers
num.printNumbers();
//print addition
Example 4
In the code example below, the only members of rect that cannot be accessed from outside the class are
width and height, since they have private access and they can only be referred to from within other
members of that same class.
// classes example
#include <iostream>
class Rectangle {
height = y;
int main ()
Rectangle rect;
rect.set_values (3,4);
return 0;
}
6.6 Class Member Functions
class Account{
public:
};
Page 19 of 29
public:
virtual string getType() { return "Current Account"; };
};
public:
virtual string getType() { return "Deposit Account"; };
};
int main()
class Account{
public:
string getType()
{ return "Generic Account"; };
Page 20 of 29
};
public:
};
public:
string getType() { return "Deposit Account"; };
};
int main()
class Box {
Page 21 of 29
double width;
public:
double length;
v. Explain the difference between internal and external definition of member functions
Page 22 of 29
UNIT SEVEN: CONSTRUCTORS AND DESTRUCTORS
Learning outcomes
7.1 Constructors
A constructor is a member function that is used for creating objects and initializing the states of the objects.
• Its name is the same as the name of the class within which it has been declared
• It is called automatically
Page 23 of 29
class Rectangle
private:
int length;
int width;
...
public:
...
};
//definition of constructor
Rectangle::Rectangle(int l, int w)
length=l;
width=w;
Since a constructor is always declared within the public section of a class, it is accessible from external
functions (these are functions that are not members of the class that has the class).
Page 24 of 29
For example the main method can call the constructor in the Rectangle class above as shown below.
This statement is a call to Rectangle constructor in a class called Rectangle. The constructor is also passed
two integer values, i.e. 6 and 5. The constructor will construct the object and 6 and 5 values will be used
as the initial state of the object. The object that will be created will be referenced by rect1 variable. If we
now want to pass a message to the object that has been created in Rectangle class, we have to use rect1 to
refer to the object as shown below rect1.find_area(); rect1 is our reference to the object created and
find_area() is the message that we are passing to our object. rect1 refers to the object created.
• Default constructors
• Copy constructors
• Parameterized constructors
a) A Default Constructor
A default constructor is a constructor that is not passed any arguments when it is called. A default
constructor can be created automatically by the compiler. For example, the default constructor for
Rectangle class above is:
class Rectangle
private: . . .
public:
Rectangle();
Page 25 of 29
...
};
Rectangle::Rectangle()
Note that the body of this constructor is empty. Now if we have a statement shown below within the main
method
int main(void)
Rectangle rect1;
...
return 0;
Statement Rectangle rect1; in the above main method is a call to the default. In that case if the Rectangle
class do not have the default constructor the compiler will create one automatically.
b) Parameterized constructors
Parameterized constructors are constructors that are passed arguments when they are called. Unlike default
constructors, parameterized constructors are not created automatically by the compiler if they are not
defined in a class. And these constructors must be defined. For example:
class Rectangle
Page 26 of 29
{
int width;
...
public:
...
};
Rectangle::Rectangle(int l, int w)
{ length=l; width=w; }
There are two ways of passing arguments to parameterized constructors when they are called: by calling
the constructor explicitly and by calling the constructor implicitly. For example Rectangle rect1=
Rectangle( 6, 5); //explicit call Rectangle rect1(6, 5); //implicit call Implicit call is the one that is normally
used.
c) Copy constructors
Copy constructors are constructors that used to create and initialize an object using another object. For
example Rectangle rect1(6, 5); //a call to a parameterized constructor Rectangle rect2(rect1); // a call to a
copy constructor to create and initialized rect2 object //using rect1 object
Page 27 of 29
7.5 Destructors
A destructor is a member function that is used to free a location that is held by an object for use by another
object.
An object is deleted when the flow of control leaves the scope within which it has been created.
For example
Rectangle::~Rectangle()
Note that just like other member functions, constructors can have default arguments and they can be
overloaded.
Page 29 of 29