Calculus5000
Calculus5000

Reputation: 427

Use of undeclared identifier C++

I’ve been learning C++ recently and I’ve been trying to create a simple class split into a header & a source file. However, I seem to keep on getting this error:

ship.cpp:21:9: error: use of undeclared identifier 'image'
        return image;
               ^
1 error generated.

I've included the source code below:

main.cpp:

#include <iostream>

#include <allegro5/allegro.h>
#include <allegro5/allegro_image.h>
#include <allegro5/allegro_native_dialog.h>

#include <ship.h>

int main(int argc, char **argv){
    ALLEGRO_DISPLAY *display = nullptr;
    ALLEGRO_BITMAP *image = nullptr;


    if(!al_init()){
        al_show_native_message_box(display, "Error", "Error", "Failed to initialise allegro", NULL, ALLEGRO_MESSAGEBOX_ERROR);
        return 0;
    }

    if(!al_init_image_addon()) {
        al_show_native_message_box(display, "Error", "Error", "Failed to initialize al_init_image_addon!", NULL, ALLEGRO_MESSAGEBOX_ERROR);
        return 0;
    }

    display = al_create_display(800,600);
      if(!display) {
        al_show_native_message_box(display, "Error", "Error", "Failed to initialize display!", NULL, ALLEGRO_MESSAGEBOX_ERROR);
        return 0;
      }


    Ship ship("image.jpg");
    al_draw_bitmap(ship.get_image(), 200, 200, 0);

    al_flip_display();
    al_rest(2);
    return 0;
}

ship.h:

#ifndef SHIP_H
#define SHIP_H
#include <iostream>
#include <allegro5/allegro.h>
#include <allegro5/allegro_image.h>

class Ship
{
    ALLEGRO_BITMAP *image;

    private:
        int width;
        int height;

    public:
        Ship(std::string image_file);
        ALLEGRO_BITMAP *get_image();
};

#endif

ship.cpp:

#include <allegro5/allegro.h>
#include <allegro5/allegro_image.h>
#include <allegro5/allegro_native_dialog.h>
#include <iostream>

#include <ship.h>




Ship::Ship(std::string image_file){
    image = al_load_bitmap(image_file.c_str());
    if(image == nullptr){
        std::cout << "Ship went down." << std::endl;
    }
    std::cout << "Ship loaded successfully." << std::endl;
}   


ALLEGRO_BITMAP *get_image(){
    return image;
}

Upvotes: 0

Views: 3733

Answers (2)

Olipro
Olipro

Reputation: 3529

You have defined the function incorrectly. get_image() is a member of the Ship class. Your definition creates a standalone function.

ALLEGRO_BITMAP *get_image(){

Should be:

ALLEGRO_BITMAP* Ship::get_image(){

(asterisk repositioned for readability)

Upvotes: 4

Mureinik
Mureinik

Reputation: 311723

As it's currently defined, get_image() is just a function that has nothing to do with your class. The fact that it's located in ship.cpp is inconsequential. Since you're trying to implement a method of the Ship class, you need to defined the implementation with the Ship:: prefix:

ALLEGRO_BITMAP* Ship::get_image() {
    return image;
}

Upvotes: 1

Related Questions