Thread: virtual functions in polymorphism

  1. #1
    Registered User
    Join Date
    Mar 2003
    Posts
    11

    virtual functions in polymorphism

    hey eveyrone, im doing this program on polymorphism, and what i was using to print out all the of the information was a print function and it looked like this

    virtual void print() const;

    and that worked, but now i found out my teacher wants us to use the overloaded ostream operator to print out everything but when i tried this

    virtual friend ostream&operator(ostream&,Time&);

    it gave me an error.
    please help, thanx a lot :-)

  2. #2
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    friends cant be virtual
    you need something like this...

    Code:
    class Base 
    {
    public:
       virtual ostream& print( ostream& )const = 0;
    };
    
    ostream& operator << ( ostream& os, const Base& object)
    {  return object.print(os);}
    
    
    class Derived: public Base
    {
    public:
       virtual ostream& print( ostream& strm )const
        { // print derived object
           return strm;
        }
    };
    std omitted for brevity.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  3. #3
    Registered User
    Join Date
    Mar 2003
    Posts
    11
    i used the code that you have provided, and it compiles and runs, but instead of getting the private data members, i get the address of where everything was stored.

    lets say i have

    private:
    char*stylename;
    double price;
    };
    #endif

    well how do i implement that into that virtual ostream function because all im returning is e.print(output);

    thanx a lot :-)

  4. #4
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    post your code. use code tags. read stickys at top of forum if unsure.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 48
    Last Post: 09-26-2008, 03:45 AM
  2. virtual functions
    By BKurosawa in forum C++ Programming
    Replies: 9
    Last Post: 08-12-2007, 02:12 AM
  3. Program with Shapes using Virtual Functions
    By goron350 in forum C++ Programming
    Replies: 12
    Last Post: 07-17-2005, 01:42 PM
  4. another question about virtual functions
    By SuperNewbie in forum C++ Programming
    Replies: 14
    Last Post: 01-29-2005, 09:14 AM
  5. Exporting Object Hierarchies from a DLL
    By andy668 in forum C++ Programming
    Replies: 0
    Last Post: 10-20-2001, 01:26 PM