Inheritance

W

Wilson

hi. Again trying to understand inheritcance but can't see what is
wrong with this small peice of code below to test my knowledge. When
complied it simply returns the "system("PAUSE")" and nothing else. I
cant understand why that is. Please help.

wilson


#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;

class account
{
public:
int balance, number;
virtual int function() { return balance; }
};
class checking : public account
{
public:
int balancechecking;
};
class savings : public account
{
public:
int balancesavings;
};

void display(account& x)
{
x.function();
}

int main()
{
savings a;
checking b;
b.balance = 10;
a.balance = 20;
display(a);
cout << endl;
display(b);
system("PAUSE");
}
 
J

John Harrison

Wilson said:
hi. Again trying to understand inheritcance but can't see what is
wrong with this small peice of code below to test my knowledge. When
complied it simply returns the "system("PAUSE")" and nothing else. I
cant understand why that is. Please help.

wilson


#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;

class account
{
public:
int balance, number;
virtual int function() { return balance; }
};
class checking : public account
{
public:
int balancechecking;
};
class savings : public account
{
public:
int balancesavings;
};

void display(account& x)
{
x.function();
}

int main()
{
savings a;
checking b;
b.balance = 10;
a.balance = 20;
display(a);
cout << endl;
display(b);
system("PAUSE");
}

What did you expect it to do? You have a function called display, but it
doesn't display anything. This has got nothing to do with inheritance.

Perhaps you meant this

cout << display(a);
cout << endl;
cout << display(b);

I always think that confused names in a program is a symptom of confused
thinking. Don't use names like 'function' and 'display', think about
what the methods and functions actually do and give them proper names,
this will help avoid mistakes like this.

For instance the method you called 'function', should be called
'get_balance' (or something similar), and the function you called
'display' should also be called 'get_balance' (or you should just get
rid of it altogether). With a proper names you would not have fooled
yourself into thinking that you had written a function that would
display something.

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,191
Latest member
BuyKetoBeez

Latest Threads

Top