nhershy
nhershy

Reputation: 755

Can C++'s class variables be initialized without a constructor like in Java?

In Java I could create a class and initialize a variable without a constructor:

public class Foo {
private int x = 1;
public getx() {
    return x;
    }
}

But in c++, to accomplish the same thing, the only way I know how is to do this:

class Foo
{
private:
    int x;
public:
    Foo()
    {
        x = 1;
    }
    getx()
    {
        return x;
    }
};

Upvotes: 1

Views: 74

Answers (1)

Amadeus
Amadeus

Reputation: 10655

Since C++11 you can do this. In other words, this works pretty well:

class Foo
{
    int x = 1;
public:
    int getX() { return x;}
};

Upvotes: 3

Related Questions