McP
McP

Reputation: 823

Initialise static const, non-integral, class member with a private member

Im am attempting to initialise a static const non-integral. However it requires parameters which are private. If it was of integral type you could place it in the class body and allow allow one variable to take the value of another ie

static const int A=0;
static const int B=A;

But as its non-integral it must be initialised outside of the class body, but as the members are private they are out of scope, outside the class body.

For example

//HEADER
class Person
{
    static const float x;
    static const float y;
    static const int rad;
    static const sf::Color col;
    static const sf::Shape shape;
};

//CPP
const float Person::x=0;
const float Person::y=0;
const int Person::rad=16;
const sf::Color Person::col(255,0,0,255);
const sf::Shape shape=sf::Shape::Circle(Person::x,Person::y,Person::rad,Person::col);

Person::x,Person::y,Person::rad,Person::col is out of scope as they are private. As I am initialising a static const I would wish not to put it in the constructor which would be called everytime a new instance is created.

For example

//HEADER
class Person
{
    static const float x;
    static const float y;
    static const int rad;
    static const sf::Color col;
    static const sf::Shape shape;

    Person();
};

//CPP
const float Person::x=0;
const float Person::y=0;
const int Person::rad=16;
const sf::Color Person::col(255,0,0,255);

Person::Person()
{
    const sf::Shape shape=sf::Shape::Circle(x,y,rad,col);
}

The above seems to work however I wish not to use it for the above reason.

Is there a work around. Without making the members public.

Thanks

Upvotes: 2

Views: 823

Answers (2)

Johan Lundberg
Johan Lundberg

Reputation: 27038

Do not use static value from the class to calculate other static values. In this case it is possible, if you keep things in the right order ( Static variables initialisation order )

The design of your classes are suspicious. If x,y,rad,col are only used in circle, it may be better to just initialize your default circle and not have those variables at all.

change

static const float x ;

into

static float x() { return 0 ; }

etc.

Upvotes: 0

Drew Dormann
Drew Dormann

Reputation: 63830

Add this public function to your Person class.

static const sf::Shape defaultShape();

This function can both access the private variables and initialize your static Shape variable.

Upvotes: 1

Related Questions