xxxxxxxxxx
class House {
private:
std::string location;
int rooms;
public:
// Default constructor
House() {
location = "New York";
rooms = 5;
}
// Constructor with parameters
House(std::string loc, int num) {
location = loc;
rooms = num;
}
void summary() {
std::cout << location << " house with " << rooms << " rooms.\n";
}
};
xxxxxxxxxx
class House {
private:
std::string location;
int rooms;
public:
// Constructor with default parameters
House(std::string loc = "New York", int num = 5) {
location = loc;
rooms = num;
}
void summary() {
std::cout << location << " house with " << rooms << " rooms.\n";
}
};
xxxxxxxxxx
int main() {
House green_house("Boston", 3); // Calls House(std::string, int) constructor
green_house.summary();
return 0;
}
xxxxxxxxxx
int main() {
House default_house; // Calls House("New York", 5), default
House texas_house("Texas"); // Calls House("Texas", 5)
House big_florida_house("Florida", 10); // Calls House("Florida", 10)
}
xxxxxxxxxx
House big_house(10); // Error: no constructor to handle House(int)
xxxxxxxxxx
// C++ program to show how to call parameterized Constructor
// of base class when derived class's Constructor is called
#include <iostream>
using namespace std;
// base class
class Parent {
int x;
public:
// base class's parameterized constructor
Parent(int i)
{
x = i;
cout << "Inside base class's parameterized "
"constructor"
<< endl;
}
};
// sub class
class Child : public Parent {
public:
// sub class's parameterized constructor
Child(int x): Parent(x)
{
cout << "Inside sub class's parameterized "
"constructor"
<< endl;
}
};
// main function
int main()
{
// creating object of class Child
Child obj1(10);
return 0;
}
/*
Inside base class's parameterized constructor
Inside sub class's parameterized constructor
*/