slayton
slayton

Reputation: 20309

Proper header file syntax

I'm trying to understand when it is required to declare a function in a header file when inheriting methods from a parent class.

For example lets say I have the following class:

class parent{
public:
    virtual void foo()= 0;
}

Lets say I have a child class that inherits from parent do I have to also declare foo in child's header file or can I simply define the method in the source file for child?

Would the following delaration be incorrect?

Headerfile:

class child : public parent{
}

Classfile:

child::foo(){
// do something
}

Upvotes: 0

Views: 481

Answers (3)

Alok Save
Alok Save

Reputation: 206586

Non virtual methods from a base class are inherited in child class so you do not need to define or declare them again in child class, A non virtual method called on an derived class object will simply call the method defined in Base class(provided access specifier rules allow you to)

if you declare an method from base class again in Derived class then it declares a new method in derived class which hides all the base class methods with the same name. This is called as Function Hiding.

Good Read:

What's the meaning of, Warning: Derived::f(char) hides Base::f(double)?

In case of virtual methods you do not need to declare the Base class method again in Child class, You just need to provide a definition. This is called as Function Overidding.

Upvotes: 1

Jonathan Leffler
Jonathan Leffler

Reputation: 754590

You do not have to declare foo() in the child's class definition or its header. It is inherited automatically - that's what inheritance means. (Of course, the function would have to be public rather than private in the base class (parent), but that's a minor peccadillo.)

You simply define the method in the source file for the child class.

Upvotes: 0

Calvin Froedge
Calvin Froedge

Reputation: 16373

Header file:

class Class : public Parent {

public:
    void myMethod();
}

Source file:

void Class::myMethod(){

}

Upvotes: 0

Related Questions