CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 10 of 10
  1. #1
    Join Date
    Oct 2005
    Location
    Chennai, India
    Posts
    27

    Accessing derived class members using base class pointer.

    Friends,

    Can a base class reference be used to access derived class-specific members? Note that the members are not part of the base class, only part of the derived class.

    Thank You,
    Paramesh.

  2. #2
    Join Date
    Aug 2005
    Posts
    132

    Re: Accessing derived class members using base class pointer.

    The direct answer is no. If you have an object of the base class and you wish to access members of a child class of that base class then you cannot access them as the object you have is not of that object type and the data does not exist.

  3. #3
    Join Date
    Apr 1999
    Location
    Altrincham, England
    Posts
    4,470

    Re: Accessing derived class members using base class pointer.

    ...and a need to do so indicates a probable flaw in the design.
    Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
    --
    Sutter and Alexandrescu, C++ Coding Standards

    Programs must be written for people to read, and only incidentally for machines to execute.

    --
    Harold Abelson and Gerald Jay Sussman

    The cheapest, fastest and most reliable components of a computer system are those that aren't there.
    -- Gordon Bell


  4. #4
    Join Date
    Oct 2000
    Location
    London, England
    Posts
    4,773

    Re: Accessing derived class members using base class pointer.

    It cannot access them directly, but a call to the base-class function may invoke calls in the derived class, either if the function called is virtual or if the function itself calls virtual functions.

  5. #5
    Join Date
    Feb 2005
    Location
    Normandy in France
    Posts
    4,590

    Re: Accessing derived class members using base class pointer.

    Quote Originally Posted by cegparamesh

    Can a base class reference be used to access derived class-specific members? Note that the members are not part of the base class, only part of the derived class.
    If you are sure the reference is actually a reference to the derived class, you can use static cast, like that:
    Code:
    static_cast<Derived*>(&reference_variable)->DerivedMember(arguments);
    However, doing such thing is often due to a design flaw.

    If the base class contains one or more virtual functions (pure or not), you can use dynamic_cast as debugging purposes : it returns NULL if the reference is not actually a reference to the derived class, thus it checks logical bugs.
    I don't like this usage of dynamic_cast in a release project. However it may be used in a project compiled in debug mode.
    "inherit to be reused by code that uses the base class, not to reuse base class code", Sutter and Alexandrescu, C++ Coding Standards.
    Club of lovers of the C++ typecasts cute syntax: Only recorded member.

    Out of memory happens! Handle it properly!
    Say no to g_new()!

  6. #6
    Join Date
    Oct 2005
    Location
    Chennai, India
    Posts
    27

    Re: Accessing derived class members using base class pointer.

    Thank You friends.

    How would i use the static cast?
    When i do like this, error message comes up.
    Code:
    Base *b = static_cast<Derived*>(&reference_variable)->DerivedMember(arguments);
    Thank you,
    Paramesh.

  7. #7
    Join Date
    Feb 2005
    Location
    Normandy in France
    Posts
    4,590

    Re: Accessing derived class members using base class pointer.

    What is your exact code?
    What does the DerivedMember returns?

  8. #8
    Join Date
    Oct 2005
    Location
    Chennai, India
    Posts
    27

    Re: Accessing derived class members using base class pointer.

    Here is the code:
    Code:
    #include <iostream>
    using namespace std;
    
    class base
    {
    public:
        virtual void printbase()
        {
            cout<<"Inside the base class..."<<endl;
        }
    };
    
    class derived:public base
    {
    public:
        void printderived()
        {
            cout<<"Inside the derived class..."<<endl;
        }
    };
    
    int main()
    {
        base *s = new base();
        s->printbase();
        
        delete(s);
    
        derived d;
        
        base *as = static_cast<derived*>(&d)->printderived();
    
        getchar();
        getchar();
        return 0;
    }
    Thank You,
    Paramesh.

  9. #9
    Join Date
    Jan 2004
    Location
    Düsseldorf, Germany
    Posts
    2,401

    Re: Accessing derived class members using base class pointer.

    Quote Originally Posted by cegparamesh
    Thank You friends.

    How would i use the static cast?
    When i do like this, error message comes up.
    Code:
    Base *b = static_cast<Derived*>(&reference_variable)->DerivedMember(arguments);
    Thank you,
    Paramesh.
    It depends what reference_variable is? If it is of type Base&, you can do
    Code:
    Derived & d = static_cast<Derived&>(reference_variable);
    d.DerivedMember(argument);
    If reference_variable is of type Base* it is pretty similar:
    Code:
    Derived * d = static_cast<Derived*>(reference_variable);
    d->DerivedMember(argument);
    However, if it of type Base, then you have casted your Derived object to an object of class Base and there is no way to cast it back.

  10. #10
    Join Date
    Jan 2004
    Location
    Düsseldorf, Germany
    Posts
    2,401

    Re: Accessing derived class members using base class pointer.

    Quote Originally Posted by SuperKoko
    If you are sure the reference is actually a reference to the derived class, you can use static cast, like that: [...]
    However, doing such thing is often due to a design flaw.
    I've heard and read this a lot, but cannot really agree that using static_cast implies a design flaw.

    I often have members of different classes in a container (vector, map, ...) and want to do an operation on members of one type only. The typical way of doing that for me, is to loop through the container, check the type of an object
    and, if it is of the type I want, static_cast it and perform the operation.

    Now there are a lot of operations, which are specific to the derived classes and declaring them all for the parent class (and defining them empty) would imho unnecessarily blow up the parent class.

    An example:
    Code:
    class FileSystemObject
    {
      virtual bool isFolder() const = 0;
      // ...
    }
    
    class Folder : public FileSystemObject
    {
      // ...
      virtual bool isFolder() const { return true; }
      vector<FileSystemObject*> contents;
    }
    
    class File : public FileSystemObject
    {
      // ...
      virtual bool isFolder() const { return false; }
    }
    
    // Find all files under Folder basefolder that match a criterion
    template <typename F>
    vector<File*>* find(Folder* basefolder, F criterion, vector<File*>* result = 0)
    {
      if (! result) result = new vector<File*>;
      vector<File*>::iterator it = basefolder.contents.begin();
      while( it != basefolder.contents.end() {
        if ( (*it)->isFolder() ) {
          find(static_cast<Folder*>(*it), criterion, result);
        } else {
          File * f = static_cast<File*>(*it);
          if (criterion(f)) result->push_back(f);
        }
        ++it;
      }
      return result;
    }
    Now I know, there are ways to implement this without static_cast, but are those really better ways? Should class FileSystemObject really have member functions for everything that the derived objects are capable off? I don't think so.

    Please note that the above code is writte for demonstration of why I use static_casts, and thus ignores things like data encapsulation, public/private declaration and there are certainly typos as well.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured