Thread: Inheritance question.

  1. #1
    Registered User
    Join Date
    Sep 2004
    Posts
    80

    Inheritance question.

    I'm wondering about the syntax for inheritance and why I have to use public like this:
    Code:
    class myClass: public myBase

  2. #2
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    Quote Originally Posted by antex
    I'm wondering about the syntax for inheritance and why I have to use public like this:
    Code:
    class myClass: public myBase
    You don't have to but if you inherit privately or protected you are not able to access the methods of myClass via a pointer to myBase

    try this

    Code:
    class myBase {
    public:
        virtual void do_sth() = 0;
        void do_sth_else() {}
    };
    
    class myClass: public myBase {
    //class myClass: private myBase {
    public:
        virtual void do_sth() { do_sth_else(); }    
    };
    
    
    int main() {
        myClass mc;
        mc.do_sth();
        
        myBase * bp = new myClass;
        bp->do_sth();
    }
    ant try what happens if you change public to private or protected.
    Kurt

  3. #3
    Registered User
    Join Date
    Apr 2004
    Posts
    173
    Expanding upon what ZuK said, basically the access control level determines the access levels for the derived class.

    So if you want all the access levels to be the same as what is in the base class, you derive it publicly. Otherwise, if you want to make all the members of the base class private in the derived class, you derive it privately. And lastly, if you want the public/protected members of the base class to be protected in the derived class, you derive it protected(ly).
    The cost of software maintenance increases with the square of the programmer's creativity.

  4. #4
    Registered User
    Join Date
    Sep 2004
    Posts
    80
    Ok, I see, this made it much easier to understand. Thank you both!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Noob question about templates & inheritance
    By blacknail in forum C++ Programming
    Replies: 9
    Last Post: 10-25-2008, 01:51 PM
  2. Virtual inheritance
    By 6tr6tr in forum C++ Programming
    Replies: 13
    Last Post: 05-07-2008, 11:20 AM
  3. opengl DC question
    By SAMSAM in forum Game Programming
    Replies: 6
    Last Post: 02-26-2003, 09:22 PM
  4. Inheritance vs Composition
    By Panopticon in forum C++ Programming
    Replies: 11
    Last Post: 01-20-2003, 04:41 AM
  5. Very simple question, problem in my Code.
    By Vber in forum C Programming
    Replies: 7
    Last Post: 11-16-2002, 03:57 PM