addousas
addousas

Reputation: 189

C++ Object Initialization outside main

I have some C++ code that produces an error:

class foo{
  public:
    int a; 
    int b;
};

foo test;
test.a=1;   //error here
test.b=2;

int main()
{
    //some code operating on object test
}

I get this error:

error: expected constructor, destructor, or type conversion before '.' token

What does the error mean and how do I fix it?

Upvotes: 0

Views: 6200

Answers (4)

Some programmer dude
Some programmer dude

Reputation: 409482

It's called a constructor. Include one that takes the wanted values as arguments.

Like

class foo
{
public:
    foo(int aa, int bb)
        : a(aa), b(bb)  // Initializer list, set the member variables
        {}

private:
    int a, b;
};

foo test(1, 2);

As noted by chris, you can also use aggregate initialization if the fields are public, like in your example:

foo test = { 1, 2 };

This also works in C++11 compatible compilers with the constructor as in my example.

Upvotes: 3

anhoppe
anhoppe

Reputation: 4507

You cannot call the variable initialization outside a function. As mentioned in a comment

test.a=1
test.b=2

is thus invalid. If you really need an initialization, use a constructor like

class foo
{
public:
    foo(const int a, const int b);

    int a;
    int b;
}

Otherwise you could put the initialization e.g. into the main function.

Upvotes: 0

yizzlez
yizzlez

Reputation: 8805

You need a default constructor:

//add this
foo(): a(0), b(0) { };
//maybe a deconstructor, depending on your compiler
~foo() { };

Upvotes: 0

Geoffrey
Geoffrey

Reputation: 11374

This should be:

class foo
{
  public:
    int a; 
    int b;
};

foo test;
int main()
{
  test.a=1;
  test.b=2;
}

You can not write code outside of a method/function, you can only declare variables/classes/types, etc.

Upvotes: 1

Related Questions