I'm having trouble compiling a C ++ program in IDE Code :: Blocks. What I'm trying to do is access an object that was instantiated inside a conditional If. I will put down the codes of the main program and also of the classes that I created.
User Class (parent class of Student and Teacher):
#ifndef UTILIZADOR_H
#define UTILIZADOR_H
#include <string>
using namespace std;
class Utilizador{
private:
string name;
int access_level;
public:
//Setters
void setName(string name);
void setAccessLevel(int level);
//Getters
string getName();
int getAccessLevel();
};
#endif // UTILIZADOR_H
Teacher class inherits from User:
#ifndef PROFESSOR_H
#define PROFESSOR_H
#include <string>
#include "Utilizador.h"
using namespace std;
class Professor : public Utilizador{
private:
public:
//Constructor Method
Professor(string name);
};
#endif // PROFESSOR_H
Student Class inherits from User:
#ifndef ALUNO_H
#define ALUNO_H
#include <string>
#include "Utilizador.h"
using namespace std;
class Aluno : public Utilizador{
private:
double *nota = new double; //Store an array of data with the scholar grades of the student during the year
public:
//Constructor method
Aluno(string name);
};
#endif // ALUNO_H
Below the main program code, where I try to implement the object:
#include <iostream> //Input and Output library
#include <windows.h>
#include <vector>
#include <string>
#include "include/Aluno.h"
#include "include/Professor.h"
using namespace std;
int main()
{
//Below, this variables have the function of receive the input of data
string nome;
int nivel;
//First contact with the user, request data entry
cout << "Bem vindo ao programa de operacoes matematicas, vamos comecar!\n\n";
cout << "Informe seu nome: ";
cin >> nome; cout << endl;
cout << "Agora informe qual o seu tipo de utilizador para poder oferecer-mos a melhor experiencia. (1) Professor / (2) Aluno: ";
cin >> nivel; cout << endl;
//Creating the object depending of the data that the user inserted in previous step
if(nivel == 1){
Professor *a = new Professor(nome);
a->setAccessLevel(nivel);
}else{
Aluno *a = new Aluno(nome);
a->setAccessLevel(nivel);
}
cout << a->getName(); //Linha que consta o erro de Compilação!
return 0;
}
In the code of the main program you can see that I create the object depending on the level of the user so I do it inside the if
conditional, but at the time of compiling and running the program Code :: Blocks says the following:
"error: 'a' was not declared in this scope".
I do not understand why it does not recognize that the object will be instantiated in the a
variable.
If I create the object outside the conditional it works quietly when I try to access the methods.