Thread: inheritance & virtual functions

  1. #1
    Registered User
    Join Date
    Jan 2002
    Posts
    11

    inheritance & virtual functions

    Hello,

    I have an abstract base class called Node, which has got two derived classes, IntNode and StringNode.

    class Node{ //abstract class
    private:
    Node* lnk;
    public:
    Node();
    virtual ~Node();
    void link(Node* n);
    Node* link() const;
    virtual void print()const=0;
    };

    class IntNodeublic Node{
    …//code here!
    };

    class StringNodeublic Node{
    …//code here!
    };

    My question is, when I write:
    Node* myNode=new IntNode;

    I do not have access to the member functions in class IntNode (they are declared as public), I have only access to the functions in the base class, but when I write:

    IntNode* myNode= new IntNode;

    I have access to all of the member functions, both base and derived.

    What is really the difference between these two statements? And when should they be used? And what shall I do in order to be access the member functions?

    Cheers!
    I use BorlandBuilder 5

  2. #2
    Registered User samGwilliam's Avatar
    Join Date
    Feb 2002
    Location
    Newport
    Posts
    382
    Because node is a pointer to the base class, you can only access (with ->) the base functions.
    Current Setup: Win 10 with Code::Blocks 17.12 (GNU GCC)

  3. #3
    S­énior Member
    Join Date
    Jan 2002
    Posts
    982
    If you only have a base pointer, then without casting you can only call base methods, regardless of the type of inheritence you're using. You'll either have to create an interface for all the derived functions in the base class (making them pure if necessary), cast (using dynamic_cast if you want to be safe), or re-design (templates ??).

  4. #4
    Registered User samGwilliam's Avatar
    Join Date
    Feb 2002
    Location
    Newport
    Posts
    382
    If I wanted a parrot, I'll go to the pet shop!
    Current Setup: Win 10 with Code::Blocks 17.12 (GNU GCC)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 11-17-2008, 01:00 PM
  2. virtual functions
    By lord in forum C++ Programming
    Replies: 9
    Last Post: 10-18-2008, 02:55 PM
  3. Program with Shapes using Virtual Functions
    By goron350 in forum C++ Programming
    Replies: 12
    Last Post: 07-17-2005, 01:42 PM
  4. Exporting Object Hierarchies from a DLL
    By andy668 in forum C++ Programming
    Replies: 0
    Last Post: 10-20-2001, 01:26 PM
  5. Multiple virtual inheritance
    By kitten in forum C++ Programming
    Replies: 3
    Last Post: 08-10-2001, 10:04 PM