I looked everywhere for an answer but can't find one. Below is my short program in visual studio 2017. It does not print neither of the "rooms" I added - it posts random values. The code compiles perfectly. just the output is wrong. Most the code is irrelevant I think, I just honestly don't know WHAT I did wrong. I think its probably in the vector/inheritance parts.
EDIT: SOLVED quickly. I inserted a local variable's pointer to my vector. thanks.
Room.h :
#pragma once
#include <vector>
class Room {
protected:
int i;
int j;
int size;
char** objs;
public:
Room(int _i = 0, int _j = 0, int _size = 0);
int get_i() const { return i; }
int get_j() const { return j; }
int get_size() const { return size; }
char** get_objs() const { return objs; }
virtual void make_room() = 0;
};
class Maze : public Room {
public:
Maze(int _i, int _j, int _size);
void make_room();
};
class Board {
std::vector<Room*> rooms;
public:
Board() {}
void add_room(int i, int j, int v);
void print_a_room() const;
};
Room.cpp:
#include "room.h"
#include <iostream>
Room::Room(int _i, int _j, int _size) : i(_i), j(_j), size(_size) {
objs = new char*[_size];
for (int i = 0; i < _size; i++) {
objs[i] = new char[_size];
for (int j = 0; j < _size; j++) {
objs[i][j] = ' ';
}
}
}
Maze::Maze(int _i, int _j, int _size) : Room(_i, _j, _size) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
objs[i][j] = '*';
}
}
make_room();
}
void Maze::make_room() {
int x = 1;
}
void Board::add_room(int i, int j, int v) {
rooms.push_back(&Maze(i, j, v));
}
void Board::print_a_room() const {
Room* r = rooms.back();
std::cout << r->get_i() << "," << r->get_j() << std::endl;
}
main.cpp:
#include "room.h"
#include <iostream>
int main() {
Board b;
b.add_room(1, 2, 10);
std::cout << "hello" << std::endl;
b.add_room(3, 4, 5);
b.print_a_room();
return 0;
}
Help will be greatly appreciated.