473,795 Members | 3,386 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2606
"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(25 6);
arr[0] -add_int();
arr[0] -show();

arr[1] = &Savings(102 4);
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...@googlem ail.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****@googlem ail.comwrote in message
news:11******** *************@p 15g2000hsd.goog legroups.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*******@rock etmail.comwrote in message
news:uY******** *******@newsfe0 2.lga...
"Wilson" <tp****@googlem ail.comwrote in message
news:11******** *************@p 15g2000hsd.goog legroups.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...@rock etmail.comwrote :
"Wilson" <tpw...@googlem ail.comwrote in message

news:11******** *************@p 15g2000hsd.goog legroups.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::check ing()
{
checking::balan ce = 10;
cout << endl;
}
int a;
};

class savings : public account
{
public:
savings::saving s()
{
savings::balanc e = 20;
cout << endl;
}
int b;
};

int main()
{
checking one;
savings two;
one.returnbalan ce();
two.returnbalan ce();
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::check ing()
{
checking::balan ce = 10;
cout << endl;
}
int a;
};

class savings : public account
{
public:
savings::saving s()
{
savings::balanc e = 20;
cout << endl;
}
int b;
};

int main()
{
checking one;
savings two;
one.returnbalan ce();
two.returnbalan ce();
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(instrumen ts[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
4429
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 one vtbl ptr BUt when I derive the class B from class A (both have 1 virtual function each ) the size remains still as 4 bytes . class A = 4 bytes class B :public A = 4 bytes class...
5
2927
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 virtual function plus redefinitions of the three inherited virtual functions. Following is a simplified code fragment to illustrate my code and my problem:
18
2225
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
2351
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
1682
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 address of a virtual function is resolved and what the hidden costs associated with virtual functions are? I've heard the same of typeof (that it is inefficient if used in high traffic code) -- if you've the time, could you explain how typeof works...
25
5422
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 a lot are the ones that are virtual and thus will slow down the calculation, at least that is what what I have read on several places on the internet. It makes sense the program has to work with some kind off lookup table for the virtual...
11
4369
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 it inline. Like this.
7
313
by: ashishnh33 | last post by:
i want to know about the concept behind the virtual functions.
5
1993
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 override it or not? In such cases what would be the access levels of those functions in both base and derived classes? struct AbstractBase { virtual void mandatory_func() = 0; virtual void optional_func() { }
14
4212
by: v4vijayakumar | last post by:
Why we need "virtual private member functions"? Why it is not an (compile time) error?
1
10164
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10001
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9042
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7538
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6780
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5437
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5563
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4113
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2920
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.