W4L2
W4L2
Indranil Saha
CS253: Software Development and Operations Object-Oriented Programming Using C++ 1/9
Class
Box class
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
CS253: Software Development and Operations Object-Oriented Programming Using C++ 2/9
Object
CS253: Software Development and Operations Object-Oriented Programming Using C++ 3/9
Example:Classes and Objects
Box class and its objects
#include <iostream>
using namespace std;
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
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
CS253: Software Development and Operations Object-Oriented Programming Using C++ 4/9
Member Functions
A function that has its definition or its prototype within the class
definition like any other variable.
It operates on any object of the class of which it is a member
Has access to all the members of a class for that object.
double Box::getVolume(void) {
return length * breadth * height;
}
double getVolume(void) {
return length * breadth * height;
}
};
CS253: Software Development and Operations Object-Oriented Programming Using C++ 5/9
Invocation of Member Functions
CS253: Software Development and Operations Object-Oriented Programming Using C++ 6/9
Example: Member Functions
Box class with functions
#include <iostream>
using namespace std;
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
CS253: Software Development and Operations Object-Oriented Programming Using C++ 7/9
Example: Member Functions (Contd.)
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
CS253: Software Development and Operations Object-Oriented Programming Using C++ 8/9
Object-Oriented Programming Using C++
Classes and Objects
Indranil Saha
CS253: Software Development and Operations Object-Oriented Programming Using C++ 9/9