Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ inheritance (overriding constructors)

I am learning OpenGL w/ C++. I am building the asteroids game as an exercise. I'm not quite sure how to override the constructors:

projectile.h

class projectile
{

protected:
    float x;
    float y;

public:

    projectile();
    projectile(float, float);

    float get_x() const;
    float get_y() const;

    void move();
};

projectile.cpp

projectile::projectile()
{
    x = 0.0f;
    y = 0.0f;
}

projectile::projectile(float X, float Y)
{
    x = X;
    y = Y;
}

float projectile::get_x() const
{
    return x;
}

float projectile::get_y() const
{
    return y;
}

void projectile::move()
{
    x += 0.5f;
    y += 0.5f;
}

asteroid.h

#include "projectile.h"

class asteroid : public projectile
{
    float radius;

public:
    asteroid();
    asteroid(float X, float Y);
    float get_radius();
};

main.cpp

#include <iostream>
#include "asteroid.h"

using namespace std;

int main()
{
    asteroid a(1.0f, 2.0f);

    cout << a.get_x() << endl;
    cout << a.get_y() << endl;
}

error I'm getting:

main.cpp:(.text+0x20): undefined reference to `asteroid::asteroid(float, float)'
like image 816
Mike Glaz Avatar asked Jan 17 '26 22:01

Mike Glaz


1 Answers

You can use the : syntax to call the parent's constructor:

asteroid(float X, float Y) : projectile (x ,y);
like image 186
Mureinik Avatar answered Jan 20 '26 11:01

Mureinik