June
June

Reputation: 55

c++ inheritence base and sub class

This is my base class Shape.h

#ifndef Shape_H
#define Shape_H

#include <iostream>
using namespace std;

class Shape
{
    protected:
    string name;
    bool containsObj;

public:
    Shape();
    Shape(string, bool);
    string getName();
    bool getContainsObj();
    double computeArea();
};

   #endif

Shape.cpp

#include "Shape.h"

Shape::Shape(string name, bool containsObj)
{
    this -> name = name;
    this -> containsObj = containsObj;
}
string Shape:: getName()
{
return name;
}
bool Shape::getContainsObj()
{
    return containsObj;
}

and this is my sub class. Cross.h

#ifndef Cross_H
#define Cross_H

#include <iostream>
#include "Shape.h"
using namespace std;

class Cross: public Shape
{
protected:
    int x[12];
    int y[12];
public:
    Cross();
    double computeArea();

};

#endif

Cross.cpp

#include "Cross.h"

Cross::Cross()
{

    for (int i = 0; i < 12; i++)
    {
        this -> x[i] = 0;
        this -> x[0] = 0;
    }

}

Shape and Cross are in different files, but inside the same folder. The weird thing is when i compile this, errors that i have never seen before came up such as "In function 'ZN5CrossC1Ev', undefined reference to Shape::Shape(),'ZN5CrossC1Ev', undefined reference to Shape::Shape(), undefined reference to WinMain@16".

I tried to do some debugging myself. When i remove the Cross constructor, it works fine. But i definitely need it. Can anyone explain this to me?

Upvotes: 0

Views: 134

Answers (2)

Mike Seymour
Mike Seymour

Reputation: 254431

You've declared a default constructor for Shape, but not defined it anywhere. The default constructor for Cross uses it implicitly to initialise its base class.

You options are:

  • Define the constructor, if you want Shape to be default-constructible;
  • Otherwise, remove the declaration and get Cross to initialise Shape with the other constructor.

Upvotes: 2

Edward A
Edward A

Reputation: 2310

You didn't define the default constructor but you declared it Shape();. The only constructor you defined is the one with string and bool parameters Shape(string, bool);.

adding

Shape::Shape()
{
}

or removing

Shape();

will fix it.


For future debugging read the error more carefully, it explains exactly whats wrong:

undefined reference to Shape::Shape()

Upvotes: 4

Related Questions