decare an object in c++ code example
Example 1: how to write a class in c++
class Rectangle
{
int width, height;
public:
void set_values (int,int);
int area() {return width*height;}
};
void Rectangle::set_values (int x, int y)
{
width = x;
height = y;
}
Example 2: Write a C++ program using class and objects. You have to define multiple-member functions outside class and all those functions will be the same name
#include <iostream>
using namespace std;
class Box {
public:
double length;
double breadth;
double height;
double getVolume(void);
void setLength( double len );
void setBreadth( double bre );
void setHeight( double hei );
};
double Box::getVolume(void) {
return length * breadth * height;
}
void Box::setLength( double len ) {
length = len;
}
void Box::setBreadth( double bre ) {
breadth = bre;
}
void Box::setHeight( double hei ) {
height = hei;
}
int main() {
Box Box1;
Box Box2;
double volume = 0.0;
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}