‘bar’ was not declared in this scope

From Cppsyntax

Jump to: navigation, search

You will get the error

 ‘bar’ was not declared in this scope

if the compiler can't figure out what 'bar' is.

Contents

Local variables

If bar is a local variable, you either forgot to declare it or made a typo when you did.

Forgot to declare

WRONG

 int wacka()
 {
   bar = 2;       // i not declared; compiler doesn't know if bar is an int, double, long, short, uint...
 };

RIGHT

 int wacka()
 {
   int bar = 2;       // ahhh... bar is now an int
 };

Typo

WRONG

 int wacka()
 {
   int bra;
   bar = 2;       // oops, declared "bra" but not "bar"
 };

RIGHT

 int wacka()
 {
   int bar;       // ahhh, now declared properly
   bar = 2;      
 };

Instance variables

There are several mistakes you can make with instance variables that will confuse the compiler.

Missing header

One way that this can easily happen is if you forget to include the header that declares the instance variable, similar to how the class isn't defined in the example in:

 ‘Foo’ was not declared in this scope

Missing declaration

You can also forget to declare the instance variable, same as the case above for the local variable, but you might not notice because the declaration should have been in the include file.

WRONG

foo.h:

 class Foo 
 {
   private:
     int blort;
   public:
     int getBar();
 };

foo.cc:

 #include "foo.h"
 int Foo::getBar()
 {
   return bar;       // bar never declared
 }

RIGHT

foo.h:

 class Foo 
 {
   private:
     int blort;
     int bar;     // bar declared here
   public:
     int getBar();
 };

foo.cc:

 #include "foo.h"
 int Foo::getBar()
 {
   return bar;       
 }

Typo in declaration

Like the problem with the local variables listed above, the problem might be a typo in the declaration. It is easy to do if your declarations are in an include file, since the error will show up in the source file:

WRONG

foo.h:

 class Foo 
 {
   private:
     int bra;     // typo!
   public:
     int getBar();
 };

foo.cc:

 #include "foo.h"
 int Foo::getBar()
 {
   return bar;       
 }

RIGHT

foo.h:

 class Foo 
 {
   private:
     int bar;     // ah, much better
   public:
     int getBar();
 };

foo.cc:

 #include "foo.h"
 int Foo::getBar()
 {
   return bar;       
 }

Forgetting to specify class

Another thing that is easy to do is to forget the class specifier, so what you think is a method, the compiler thinks is a subroutine:

WRONG

foo.h:

 class Foo 
 {
   private:
     int bar;    
   public:
     int getBar(); 
 };

foo.cc:

 #include "foo.h"
 int getBar()
 {
   return bar;    // this is not a method in Foo, so the compiler doesn't know about bar
 }


RIGHT

foo.h:

 class Foo 
 {
   private:
     int bar;    
   public:
     int getBar(); 
 };

foo.cc:

 #include "foo.h"
 int Foo::getBar()
 {
   return bar;   // now the compiler realizes that getBar is in class Foo
 }
Personal tools