Object created inside conditional If it generates compiler error c ++

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 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.

    
asked by anonymous 02.01.2018 / 01:34

1 answer

1

You are trying to use the a variable outside of your scope. The scope of a local variable is only between the opening brackets { and closing } of a block, starting with its declaration onwards.

if(nivel == 1){
    Professor *a = new Professor(nome); // escopo inicia
    a->setAccessLevel(nivel);
} // escopo termina
// 'a' não está disponível aqui

similarly

else{
    Aluno *a = new Aluno(nome); // escopo inicia
    a->setAccessLevel(nivel);
} // escopo termina
// 'a' não está disponível aqui

To solve your problem, two points:

  • You must move the declaration of your variable to the same scope level as the line that has the code cout << a->getName(); . This way, this code will get access to the required variable.
  • Instead of two pointers to each of the derived classes, you should have only one pointer that points to the base class. Within the conditionals, you then allocate memory dynamically to one of the derived classes.
  • With the changes:

    int main()
    {
        Utilizador *a;
        // ...
        // Creating the object depending of the data that the user inserted in previous step
        if (nivel == 1) {
            a = new Professor(nome);
        } else {
            a = new Aluno(nome);
        }
    
        a->setAccessLevel(nivel);
        cout << a->getName();
    }
    
        
    02.01.2018 / 02:11