If you want to customize how a class initializes its members or calls functions when an object of the class is created, you have to define a constructor. Standard constructors have no parameters.
If no constructors are declared in a class, the compiler automatically provides a default constructor. On the other hand, if a class declaration contains only parameterized constructors, no default constructor is generated, and the class file has no parameterless constructor at all.
class ClassName {
public:
// create a constructor
ClassName() {
// Constructor code
}
};
int main() {
ClassName obj;
return 0;
}
#include <iostream>
using namespace std;
class Cube {
private:
int length, width, height;
public:
Cube() {
length = 4;
width = 3;
height = 4;
}
int getVolume() {
return length * width * height;
}
};
int main() {
Cube c1;
cout << c1.getVolume() << endl;
return 0;
}
48