1 Answers
- Same name as class name
- No return type
- Implicitly called just after object creation
- Used to initialize data members (initial object state)
Note:- Constructor shoudn’t be called explicitly after initialization, consider update or set function for any further changes.
Example on constructor in Cpp.
const double CALL_RATE = 1.0;
class Customer {
int m_id;
std::string m_name;
std::string m_phone;
double m_balance;
public:
Customer(int id, std::string name, std::string phone, double balance) {
m_id = id;
m_name = name;
m_phone = phone;
m_balance = balance;
}
Customer(int id, std::string name, std::string phone) {
m_id = id;
m_name = name;
m_phone = phone;
m_balance = 500;
}
void makeCall(int nmins) { m_balance -= nmins * CALL_RATE; }
void recharge(double amount) { m_balance += amount; }
double getBalance() { return m_balance; }
void display() {
// print m_id,m_name,m_phone, m_balance
}
};
int main() {
Customer c1(1001, "Scott", "9845012345", 500.0);
c1.makeCall(10);
c1.recharge(100);
c1.display();
Customer c2; //??
Customer c3(1002, "Meyers", "9845012345");
c3.display();
return 0;
};