473,387 Members | 1,515 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,387 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 2560
"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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.