Qiushi Li
Qiushi Li

Reputation: 15

Puzzle about virtual function inheritance in C++

I'm noob in C++, and I have the following header file (Header.h)

#ifndef HEADER_H
#define HEADER_H

#include <iostream>

using namespace std;

class Predicate
{
public:
    virtual void print() = 0;
};

class UnaryIntegerPredicate : public Predicate 
{
public:
    virtual void print();
};

class BiaryIntegerPredicate : public Predicate
{
public:
    virtual void print();
};

#endif

and in another separate .cpp file (Source.cpp), I tried to implement the print method, but got an "expected an expression" error.

#include "stdafx.h"
#include "Header.h"

#include <iostream>

using namespace std;

UnaryIntegerPredicate::UnaryIntegerPredicate() : Predicate()
{
    virtual void print()
    {
        cout << "int : boolean" << endl;
    }
}

what is wrong here, thanks!

Upvotes: 1

Views: 108

Answers (1)

Daniel
Daniel

Reputation: 6775

I see you are probably coming from a Java background. What you need is

void UnaryIntegerPredicate::print()
{
    cout << "int : boolean" << endl;
}

You don't need the stuff surrounding that. Since you have already declared in your header that UnaryIntegerPredicate derives from Predicate, you don't mention that again in the implementation file. You show that the print method that you are writing is the print method of the UnaryIntegerPredicate class by prefixing the name of the method with the name of the class as I have shown above.

You also don't need the virtual keyword in the cpp file because that is already specified in the header file.

Upvotes: 3

Related Questions