-
December 10th, 2010, 02:53 PM
#1
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.
-
December 10th, 2010, 03:33 PM
#2
Re: Inheritance Explanation
Originally Posted by Learned
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|