Abc
Abc

Reputation: 43

Inheritance Questions

Normally Inheritance is supposed to let the derived class have the base classes protected and public variables.

#include <iostream>
#include <vector>
#include <string>
using namespace std;

////ACCOUNT//////
class Account {
  protected:
  string name;
  int balance; 

  public:
  Account(string n) : name{n} {
      cout << name << endl;
  }
};

////SAVINGS//////
class Savings: public Account {
    Savings(string s): name{s} {
        cout << "WTFA@A@" << endl;
    }
};

int main() {
    Account wtf ("wth");
    Savings test ("EEE");
    return 0;
}

Why does that code give me an error? Should Savings have inherited the name variable from Account?

Furthermore, if I wanted to add a deposit and withdraw function to both Account and Savings, do I have to add it individually or does inheritance help with that? The Withdraw is the same for both, but the Deposit is slightly different because Savings will have an interest rate.

Upvotes: 0

Views: 93

Answers (1)

Bart Friederichs
Bart Friederichs

Reputation: 33511

Two things:

First, if you want to call the superclass' constructor, do this:

Savings(string s): Account(s) {
     ...
}

Second, you forgot to make the subclass' constructor public. Methods in classes are private by default in C++.

Upvotes: 2

Related Questions