scope in inheritance

This is a discussion on scope in inheritance within the C++ Programming forums, part of the General Programming Boards category; Hi, I have a class say, "A" which is having a pure virtual function "foo". The function foo is public ...

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    41

    scope in inheritance

    Hi,

    I have a class say, "A" which is having a pure virtual function "foo". The function foo is public in class A.
    I create another class B, which inherits from A. It defines "foo" as private.

    But if I create instance of A :

    A *pB = new B();

    pB->foo(); then this calls the private function in B.

    I wonder how does this work!

    best regards,
    shalaka

  2. #2
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,062
    I think you figured out how it works. Calling a function takes the scope of the static type's version. Of course, a virtual function will essentially redirect it to the version of the dynamic type, but at that point, it's already determined that the function is public from the static type. Or something...

    The lesson learned is, in order to maintain data-hiding, members you intend to be private (or protected) in derived classes should be declared protected in your base class.
    Last edited by SlyMaelstrom; 08-08-2006 at 10:30 PM.
    Sent from my iPadŽ

  3. #3
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,892
    Well, there are uses for having public members in the base that are hidden in the derived class. I forgot which, but I saw a discussion about this point before (probably in contrast to Java, which disallows this), and someone presented a nice use case.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 06-08-2009, 03:03 PM
  2. Getting an error with OpenGL: collect2: ld returned 1 exit status
    By Lorgon Jortle in forum C++ Programming
    Replies: 6
    Last Post: 05-08-2009, 08:18 PM
  3. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM
  4. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 10:03 AM
  5. Nested loop frustration
    By caroundw5h in forum C Programming
    Replies: 14
    Last Post: 03-15-2004, 08:45 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21