473,327 Members | 2,081 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,327 software developers and data experts.

Virtual functions

hi, i am trying to understand virtual functions, both how to create
them and how or when to use them - how they can be used to improve a
program. Below is a very simple program which i quickly made using
information gathered from a book on the subject, however this simply
returns a blank space. please help both on this program and anything
else related to virtual functions.

wilson

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

class account
{
public:
int balance, number;
int function() { cout << 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");
}

Mar 17 '07 #1
7 2553
"Wilson" writes:
hi, i am trying to understand virtual functions, both how to create
them and how or when to use them - how they can be used to improve a
program. Below is a very simple program which i quickly made using
information gathered from a book on the subject, however this simply
returns a blank space. please help both on this program and anything
else related to virtual functions.

wilson

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

class account
{
public:
int balance, number;
int function() { cout << balance; }
};
class checking : public account
{
public:
int balancechecking;
You are off to a bad start. The balance should be a member of the base
function.
<snip>

Take a look at this. I am sure you can see how things such as service
charge and interest rate could be made a part of the class, for simplicity I
coded these constants in the functions. The order of doing things in main
was dictated by the order of testing,, which is not representative of an end
user application.

#include <iostream>

using namespace std;

class Acct
{
public:
virtual void add_int() = 0;
void show() { cout << balance << endl;}
protected:
double balance;
};
//----------------
class Checking : public Acct
{
public:
Checking(double bal) {balance = bal;}
void add_int() {balance -= 15;} // monthy "service" fee
private:
};
//--------------------
class Savings : public Acct
{
public:
Savings(double bal) {balance = bal;}
void add_int() {balance *= 1.01;}
private:
};
//=====================
int main()
{
Acct* arr[2];
arr[0] = &Checking(256);
arr[0] -add_int();
arr[0] -show();

arr[1] = &Savings(1024);
arr[1] -add_int();
arr[1] -show();

cin.get();
cin.get();
}
Mar 17 '07 #2
hey
i ran your program. it worked just fine.

one change but not relevant to your problem :)
class account
{
public:
int balance, number;
int function() {
cout << balance;
return balance;
}
};

i have question?? dont you need to use virtual keyword?

thanks
sanjay

On Mar 17, 11:32 am, "Wilson" <tpw...@googlemail.comwrote:
hi, i am trying to understand virtual functions, both how to create
them and how or when to use them - how they can be used to improve a
program. Below is a very simple program which i quickly made using
information gathered from a book on the subject, however this simply
returns a blank space. please help both on this program and anything
else related to virtual functions.

wilson

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

class account
{
public:
int balance, number;
int function() { cout << 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");

}- Hide quoted text -

- Show quoted text -

Mar 17 '07 #3
"Wilson" <tp****@googlemail.comwrote in message
news:11*********************@p15g2000hsd.googlegro ups.com...
hi, i am trying to understand virtual functions, both how to create
them and how or when to use them - how they can be used to improve a
program. Below is a very simple program which i quickly made using
information gathered from a book on the subject, however this simply
returns a blank space. please help both on this program and anything
else related to virtual functions.

wilson

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

class account
{
public:
int balance, number;
int function() { cout << 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");
}
Your code isn't using any virtual functions. It would be more like this
(unchecked code and a bit non realworld):

class account
{
public:
virtual void Deposit( double Amount ) { Balance_ += Amount; }
virtual double Withdraw( double Amount ) { if ( Balance_ - Withdraw 0 )
{ Balance -= Withdraw; return Withdraw } else { return 0.0 };
virtual double Balance() { return Balance_; };
private:
double Balance_;
};

class savings: public account
{
// On savings we love you and give you and extra 0.50 on deposits
void Deposit( double Amount ) { Balance_ += Amount + 0.50; }
};

class checking: public account
{
// On Checking we charge you 0.50 to check your balance
double Balance() { Balance -= 0.50; return Balance; };
};

Play around with that.
Mar 17 '07 #4
"Jim Langston" <ta*******@rocketmail.comwrote in message
news:uY***************@newsfe02.lga...
"Wilson" <tp****@googlemail.comwrote in message
news:11*********************@p15g2000hsd.googlegro ups.com...
>hi, i am trying to understand virtual functions, both how to create
them and how or when to use them - how they can be used to improve a
program. Below is a very simple program which i quickly made using
information gathered from a book on the subject, however this simply
returns a blank space. please help both on this program and anything
else related to virtual functions.

wilson

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

class account
{
public:
int balance, number;
int function() { cout << 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");
}

Your code isn't using any virtual functions. It would be more like this
(unchecked code and a bit non realworld):

class account
{
public:
virtual void Deposit( double Amount ) { Balance_ += Amount; }
virtual double Withdraw( double Amount ) { if ( Balance_ - Withdraw >
0 ) { Balance -= Withdraw; return Withdraw } else { return 0.0 };
virtual double Balance() { return Balance_; };
private:
double Balance_;
};

class savings: public account
{
// On savings we love you and give you and extra 0.50 on deposits
void Deposit( double Amount ) { Balance_ += Amount + 0.50; }
};

class checking: public account
{
// On Checking we charge you 0.50 to check your balance
double Balance() { Balance -= 0.50; return Balance; };
};

Play around with that.
Oooh, bad code, forgot to initialize balance. account needs a constructor.

class account
{
public:
account(): Balance_(0) {};
// ...
};
Mar 17 '07 #5
On Mar 17, 10:28 pm, "Jim Langston" <tazmas...@rocketmail.comwrote:
"Wilson" <tpw...@googlemail.comwrote in message

news:11*********************@p15g2000hsd.googlegro ups.com...


hi, i am trying to understand virtual functions, both how to create
them and how or when to use them - how they can be used to improve a
program. Below is a very simple program which i quickly made using
information gathered from a book on the subject, however this simply
returns a blank space. please help both on this program and anything
else related to virtual functions.
wilson
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
class account
{
public:
int balance, number;
int function() { cout << 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");
}

Your code isn't using any virtual functions. It would be more like this
(unchecked code and a bit non realworld):

class account
{
public:
virtual void Deposit( double Amount ) { Balance_ += Amount; }
virtual double Withdraw( double Amount ) { if ( Balance_ - Withdraw 0 )
{ Balance -= Withdraw; return Withdraw } else { return 0.0 };
virtual double Balance() { return Balance_; };
private:
double Balance_;

};

class savings: public account
{
// On savings we love you and give you and extra 0.50 on deposits
void Deposit( double Amount ) { Balance_ += Amount + 0.50; }

};

class checking: public account
{
// On Checking we charge you 0.50 to check your balance
double Balance() { Balance -= 0.50; return Balance; };

};

Play around with that.- Hide quoted text -

- Show quoted text -
hi, sorry but im still confused as to how this should be written, i
aletered my origional slightly to, i thought, sort the problem however
the same problem has ocurred. Please help

Wilson

#include <iostream>
using namespace std;

class account
{
public:
virtual float returnbalance() { return balance; cout <<
balance << endl; }
float balance;
};

class checking : public account
{
public:
checking::checking()
{
checking::balance = 10;
cout << endl;
}
int a;
};

class savings : public account
{
public:
savings::savings()
{
savings::balance = 20;
cout << endl;
}
int b;
};

int main()
{
checking one;
savings two;
one.returnbalance();
two.returnbalance();
system("PAUSE");
}

Mar 18 '07 #6
"Wilson" wrote:
hi, sorry but im still confused as to how this should be written, i
aletered my origional slightly to, i thought, sort the problem however
the same problem has ocurred. Please help

Wilson

#include <iostream>
using namespace std;

class account
{
public:
virtual float returnbalance() { return balance; cout <<
balance << endl; }
float balance;
};

class checking : public account
{
public:
checking::checking()
{
checking::balance = 10;
cout << endl;
}
int a;
};

class savings : public account
{
public:
savings::savings()
{
savings::balance = 20;
cout << endl;
}
int b;
};

int main()
{
checking one;
savings two;
one.returnbalance();
two.returnbalance();
system("PAUSE");
}
Look at this link and read it carefully. Hint: note that in your code,
account is *not* "furthest".
Mar 18 '07 #7
Dnia Sun, 18 Mar 2007 05:34:52 -0700, Wilson napisa³(a):
>>hi, i am trying to understand virtual functions, both
how to create them and how or when to use them - how they
can be used to improve a program.

sorry but im still confused as to how this should be written
Maybe try this example:

#include <iostream>

class Instrument
{
public:
//The great and famous virtual function :)
virtual void MakeSound()
{
std::cout << "Some strange noise" << std::cout;
}
//In a real-world solution, this should be declared
//as pure virtual to make this class abstract type
//[not concrete instrument].
};

//Concrete example of an instrument.
class Piano : public Instrument
{
public:
//Overriding virtual function.
void MakeSound()
{
std::cout << "Plink plank plonk" << std::endl;
}
}

class Drum : public Instrument
{
public:
void MakeSound()
{
std::cout << "Crash! Bang!" << std::endl;
}
};

class Trumpet : public Instrument
{
public:
void MakeSound()
{
std::cout << "Tra ta taa!" << std::endl;
}
}

class Musician
{
public:
void Play(Instrument* ins)
{
ins->MakeSound(); //Calling virtual function.
//This will call the overrided version
//of virtual function from the derived class.
}
}

//Let's play some funky music! :)
int main()
{
//Let we create some instruments from the free store.
//Pointers to instruments will be stored in an array.
Instrument* instruments[] = {
new Trumpet(),
new Trumpet(),
new Piano(),
new Drums()
};

Musician virtuose;

//He can play every instrument we give him:
for (int i=0; i<4; ++i) virtuose->Play(instruments[i]);

//Show's over, so let's break those instruments! :P
for (int i=0; i<4; ++i) delete instruments[i];
}

Check out the output from this program.
You should see that all instruments played by musician will
make their special beautiful sounds, and not the strange noise
from the base class ;)

--
SasQ
Mar 18 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: vijay | last post by:
I have a doubt with size of classed with virtual functions I have declared A,A1,A2 ,B , C, D some classes with no varaibles but a vitual function each, The size of A is as expected 4 bytes with...
5
by: Ryan Faulkner | last post by:
Hi, Im having a few problems with virtual functions (Im using the Visual C++ environment by the way). I have a base class with three virtual functions and a derived class with a single new...
18
by: nenad | last post by:
Wouldn't it be nice if we could do something like this: class Funky{ public: auto virtual void doStuff(){ // dostuff } };
19
by: qazmlp | last post by:
class base { // other members public: virtual ~base() { } virtual void virtualMethod1()=0 ; virtual void virtualMethod2()=0 ; virtual void virtualMethod3()=0 ;
7
by: Aguilar, James | last post by:
I've heard that virtual functions are relatively ineffecient, especially virtual functions that are small but get called very frequently. Could someone describe for me the process by which the...
25
by: Stijn Oude Brunink | last post by:
Hello, I have the following trade off to make: A base class with 2 virtual functions would be realy helpfull for the problem I'm working on. Still though the functions that my program will use...
11
by: santosh | last post by:
Hello, I was going through the Marshal Cline's C++ FAQ-Lite. I have a doubt regarding section 33.10. Here he is declaring a pure virtual destructor in the base class. And again defining...
7
by: ashishnh33 | last post by:
i want to know about the concept behind the virtual functions.
5
by: Dilip | last post by:
In a polymorphic hierarchy is it common practice to have public virtual functions in the base class with a default empty implementation and let the derived classes decide whether they want to...
14
by: v4vijayakumar | last post by:
Why we need "virtual private member functions"? Why it is not an (compile time) error?
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.