0

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.

1
  • 3
    Hi, what is the error you are getting? Commented Feb 25, 2019 at 19:48

1 Answer 1

2

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++.

Sign up to request clarification or add additional context in comments.

5 Comments

"Methods are private by default in C++" - in classes, yes. In structs the default is public.
...and structs are also classes ;)
@JesperJuhl I know what you meant, I was rather refering to Bart using the term "classes" as if structs are no classes.
@user463035818 how to rephrase that then?
not sure, maybe "Methods in classes declared via class are private by default (public in classes declared with the keyword struct)".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.