0

Why is this c++ program giving me errors:

#include <iostream>
using namespace std;

int main (){
    NumbersClass num;       
    num.setNumbers(1);          
}

class NumbersClass
    {
    public:
        NumbersClass() {}           
        void setNumbers(int i) { }          
    };

Here are my errors:

taskbcplus.cpp(7): error C2065: 'NumbersClass' : undeclared identifier
taskbcplus.cpp(7): error C2146: syntax error : missing ';' before identifier 'num'
taskbcplus.cpp(7): error C2065: 'num' : undeclared identifier
taskbcplus.cpp(9): error C2065: 'num' : undeclared identifier
taskbcplus.cpp(9): error C2228: left of '.setNumbers' must have class/struct/union
1>          type is ''unknown-type''
4
  • In C++, you at least need a declaration before use (this is different than C#, for example). Commented Nov 4, 2013 at 17:11
  • @crashmstr In this case, you need the class definition too, since you are instantiating it in main. Commented Nov 4, 2013 at 17:14
  • @juanchopanza Correct, but you don't need the implementation details (i.e. the definitions could be left for after main instead of inline with the class). Commented Nov 4, 2013 at 17:17
  • @crashmstr Correct. You need the class definition, but not the definition of the member functions. Commented Nov 4, 2013 at 17:17

1 Answer 1

5

You need to put the NumberClass definition before the point at which you first instantiate it, i.e. before main.

class NumbersClass
{
public:
    NumbersClass() {}           
    void setNumbers(int i) { }          
};

int main (){
    NumbersClass num;       
    num.setNumbers(1);          
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.