Struct Question

So I've been taking C++ classes (3rd semester in school) and I have yet to come across an answer to this. We seem to be leaving the struct section of this class and I haven't seen an answer yet, so I thought I'd post here and ask.

In the following scenario:
1
2
3
4
5
6
7
8
9
10
11
12
13
struct Sped
{
    int sp;
    string de;
};

int main()
{
    Sped sp1;
    //question here

    return 0;
}


Would there be a way for me do something like:

sp1(15, "This is a string");

instead of doing:

1
2
sp1.sp = 15;
sp1.de = "This is a string";


I've been working on projects and this would make everything a heck-of-a-lot easier.
Yes. You can create constructors for structures just like classes.
'struct' is identical to 'class' with one minor difference. in a struct, the default visibility of members is public, in a class the default is private.

If you haven't covered classes yet, then I guess this doesn't help much.
In C , there is no constructor for struct. So you have to individually initiallize members.

But in C++ , structs are similar to classes and allow constructors , where you can initialize data members like
1) Sped():sp(0),de(""){}
2) Sped(int x=ix , const string& iStr):sp(ix)de(iStr){}

If you dont have a constructor , the compiler will automatically create a constructor similar to 1)

When compared to class , In struct ,
-- the members are public by default unlike class where members are private by default
-- In absence of an access-specifier for a base class/struct, public is assumed when the derived class is declared struct ( regardless of whether the base class is class type or struct type )
-- From design standpoint , you use struct is used when you have very few methods and public data

Thanks SreeB. With your post and a little more research, I was able to figure out a working method.
Even in C, you can initialize structures when they are created:
 
Sped sp1 = {15, "This is a string"};

Topic archived. No new replies allowed.