OKay... I have a newbie question.

#include <stdio.h>

class Test{
public:
    Test(int x);
};

int Test::Test(int x=0){
}

int main(){ 

Test test(1);
printf("%d", test.x);
}

My question is how to make the x variable of the constructor public.
I have tried to add :

public:
    int x = 0;

to my constructor .... but it is an another error.

I know this problem is simple, but I have been suffering with it for ... a long time

Recommended Answers

All 6 Replies

Hmm... It's to simple.
I think, you can try do like this

class Test
{
   public:
      int x;
      Test(int v = 0) :x(v) //default value
      {}
};

Well, it is work.
I don't understand the code, but is:)

Is this the easiest way to make variables that have passed to a constructor public?

The only thing I want is to make it simple...

I'll explain code
You declare variable member as public

public:
      int x;

then pass into constructor value, which you want to assign to the member variable

Test(int v = 0);

in this code parametr "v" have default value (0). You can call constructor without any arguments, and compiler assign default value to the argument.
after that, it's initializing member variable, but there is another way to initialize member variable

//like this
Test(int v = 0) :x(v) //after double point variable(value)
      {}
//or like this
Test(int v = 0)
{
   x = v;
}

This 2 pieces of code is equal

"This 2 pieces of code is equal"

well mostly the initializer list is more optimal than the second way.

Thank You:)

Test(int v = 0) :x(v) //after double point variable(value)

Could u tell me what is the name of that ":" operator ... or command.

I would like to google it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.