Methods are functions that belongs to the class.
There are two ways to define functions that belongs to a class:
In the following example, we define a function inside the class, and we name it "myMethod
".
Note: You access methods just like you access attributes; by creating an object of the class and by using the dot syntax (.
):
A constructor in C++ is a special method that is automatically called when an object of a class is created.
To create a constructor, use the same name as the class, followed by parentheses ()
:
A default constructor, also called no-argument constructor, can initialize data members to constant values.
class_name() { //body }
A parameterized constructor can initialize data members to values passed as arguments.
Syntax:
class_name(params) { //body }
Constructors can have same name differing in number and types of arugments being passed. All other function overloading rule applies to constructor overloading.
In program below, constructor Box() has two different versions.
The most common use of destructors is to deallocate memory that was allocated for the object by the constructor.
Data Abstraction can be achieved in two ways:
#include<iostream>
using namespace std;
class Box
{
private:
double width;
double height;
double depth;
float volume;
public:
Box()
{
width = 10;
height = 10;
depth = 10;
}
Box(double w,double h, double d)
{
width = w;
height = h;
depth = d;
}
void calculateVolume()
{
volume = width * height * depth;
}
void displayVolume()
{
cout<<"The volume of object is : " << volume << " m^3" <<endl;
}
~Box(){
cout<<"Destructor called."<<endl;
}
};
int main()
{
Box cube;
cube.calculateVolume();
cube.displayVolume();
Box box(2,3,5);
box.calculateVolume();
box.displayVolume();
Box same_box(box);
box.calculateVolume();
box.displayVolume();
return 0;
}
Name | Views | Likes |
---|---|---|
Arrays: Left Rotation using c++ | 726 | 1 |
C++ boost::ptr_container::ptr_set | 301 | 0 |
C++ Boost::scoped_exit | 397 | 0 |
C++ boost::ptr_inserter | 209 | 0 |
C++ Boost::ptr_container::ptr_vector.hpp | 313 | 0 |
C++ boost::shared_ptr | 620 | 0 |
C++ Boost Smart Pointers | 453 | 1 |
C++boost::simple_segregated_storage | 238 | 0 |
C++ Boost::object_pool | 223 | 0 |
OOP based programming using constructor, destructor, abstraction and encapsulation | 737 | 1 |
C++ boost::pool_allocator | 272 | 0 |
Vector-Sort | 609 | 0 |
Comments