CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Oct 2009
    Location
    NY, USA
    Posts
    191

    Inheritance Explanation

    I got this code online but I am having problem understanding it:
    Code:
    #include <iostream>
    #include <algorithm>
    #include <vector>
    #include <fstream>
    using namespace std;
    
    class Parent
    {
    public:
    	virtual void action( const char how )  //....Line 1
    	{ 
    		this->action( &how ); 
    	}
    	virtual void action( const char * how ) = 0;
    };
    
    class Son : public Parent
    {
    public:
    	using Parent::action; //....Line 2
    	void action( const char * how )
    	{
    		cout<<"Action:"<<*how<<endl; }
    };
    
    int main()
    {
    	Son s;
    	s.action( 'a' );
    
    
    	system("pause");
    	return 0;
    }
    From my previous understanding of inheritance function defined by Line 1 is redundant.
    (1) Why do we need it, since if I delete it, there is an error?

    (2) Why do we need the Line 2?

    I have walked through the debugger but I do not understand the logic of code.

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Inheritance Explanation

    Quote Originally Posted by Learned View Post
    From my previous understanding of inheritance function defined by Line 1 is redundant.
    (1) Why do we need it, since if I delete it, there is an error?
    Line 1 defines a different form of the action method, taking a different parameter. The fact that it's virtual is irrelevant; the derived class Son does not override it. In fact this is the method called in main, since a char, rather than a char*, is passed to action().

    (2) Why do we need the Line 2?
    When a derived class overrides a method, it "shadows" all other methods with the same name from farther up the hierarchy by default. There are complex reasons for this, but just take it as written. The "using" statement here tells the compiler to also look in the base class while trying to resolve the function call. This isn't needed unless you have a situation like this one, where several different methods have the same name and not all of them are overridden.

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