0
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 within an If parole. I will put down the codes of the main program and also the classes 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 code of the main program, 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 notice that I create the object depending on the level of the user so I do it within the conditional if
, but when compiling and executing the program the Code::Blocks informs the following:
"error: 'a' was not declared in this Scope".
I didn’t understand why he didn’t recognize that the object will be in any way instantiated in the variable a
.
If I create the out-of-parole object works smoothly when I try to access the methods.