0

For classes, you could just say:

class Test{
    int a;
    Test(int a);
}

Test::Test(int a) {
    this->a=a;
}

Function names get "classname::" in front of them when declared outside of class.

How would I do this for structs?

struct Test {
    int a;
    Test(int a);
}

How would I write the function for this struct Test outside of struct declaration so that it can be only be called by a Test struct?

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
user3064869
  • 530
  • 1
  • 6
  • 19
  • The difference between structs and classes is that struct members are public by default. But class members are private by default. – Playdome.io Jan 13 '15 at 13:46

4 Answers4

2

Same way. Difference between struct and class in C++ is only default visibility of members (private for class, public for struct).

Actually, it's not just function, it's constructor of class/struct Test.

ForEveR
  • 55,233
  • 2
  • 119
  • 133
0

In C++, structs are essentially the same as classes except for their default protection levels: classes default to private, structs to public. To define that function outside of the struct so that it can only be called from a member, declare it as private, then define it as normal:

struct Test {
private:
    int a;
    Test(int a);
};

Test::Test(int a) {
    this->a=a;
}

Additionally, instead of modifying the a member in the constructor body like that, you should use an initializer list. This sets the value of the member before the instance is fully constructed. It's not so important with just an int, but it's a good practice to get in to.

struct Test {
private:
    Test(int a) : a(a) {}
    int a;
};
TartanLlama
  • 63,752
  • 13
  • 157
  • 193
0

How would I write the function for this struct Test outside of struct declaration

Do exactly what you did for the first one. Both are class types, whether you use the class or struct keyword to introduce them.

The only difference is the default accessibility of members and base classes: private if you use class, and public if you use struct.

so that it can be only be called by a Test struct?

If you mean that you want it to be private (as it is in the first example), then you'll have to do so explicitly, since accessibility defaults to public:

struct Test {
    int a;
private:
    Test(int a);
};

Personally, I'd use the more conventional class if there's anything non-public.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
0

ForEveR is right. Just like in the question you can have a structure member defined like:

struct Test{
    int a;
    Test(int a);
};

Test::Test(int a) {
    this->a=a;
}

point to note, struct members are public by default. class memebers are private by default.