user3626408
user3626408

Reputation: 1

Virtual function declaration and inheritance in C++

I have a program that is trying to create derived classes from a basic abstract class. My .h file is here.

#ifndef SHIP_H
#define SHIP_H
class Ship
{
  public:
    virtual ~Ship(void) {}
    virtual const char *name(void) const = 0;
    virtual int size(void) const = 0;
    int getX(int i) const;
    int getY(int i) const;
    void print(void) const;
    bool includes(int x, int y);
int level(void) const;
void decreaseLevel(void);
static Ship *makeShip(char ch, int x1, int y1, int x2, int y2);
  protected:
    void setPos(int a1, int b1, int a2, int b2);
    int lev;
  private:
    bool checkConfig(int x1, int y1, int x2, int y2);
    int x1,y1,x2,y2;
    };

class AircraftCarrier : public Ship
{
  public:
   AircraftCarrier(int x1, int y1, int x2, int y2);
   virtual const char *name(void) const;
   virtual int size(void) const;
};

and in my Ship.cpp file I have:

const char *name (void) {

    const char * ret = "AircraftCarrier"; 
    return ret;
}

However this isn't declared in the specific scope of my derived class AircraftCarrier. However whenever I add the

const char AircraftCarrier :: *name {...}

I get an error:

Ship.cpp:46:9: error: cannot convert ‘const char*’ to ‘const char AircraftCarrier::*’ in return return ret;

Upvotes: 0

Views: 366

Answers (3)

Netherwire
Netherwire

Reputation: 2787

This definition:

const char *AircraftCarrier::name() {...}

is incorrect. Try use this, and you'll get the "member not found" compile error. Your declaration and definition must have an identical prototype. So if you're written the:

virtual const char *name(void) const;
        ^^^^^                  ^^^^^

declaration in .h, then your definition in .cpp must completely match the declaration in your proto. The right definition is:

const char* AircraftCarrier::name() const 
{
    // your complex code here
}

Upvotes: 1

alpartis
alpartis

Reputation: 1122

The name of the function you're trying to declare in Ship.cpp is AircraftCarrier::name() and that function should return a const char * based on the declaration in your header file.

const char *AircraftCarrier::name() {...}

Upvotes: 2

shf301
shf301

Reputation: 31394

It should be:

const char* AircraftCarrier :: name {...}

The * is part of the return type specification, not the functions name.

Upvotes: 0

Related Questions