I have some doubts I would like to clear regarding class, struct and union. I know class and struct are considered object. I would like to check whether union is consider object too. Whereby, I can have a constructor inside?
union ABC
{
ABC() {};
int x;
}A, B, C
Since I have object name. I could do this?
Union ABC obj1(); //Call constructor?
A.x; //Variable accessing the member
??? Secondly, what if i typedef union. What does ABC mean? Can I do this
union ABC obj1();
A.x;
typedef union ABC
{
ABC() {};
int x;
}A, B, C
The difference between a struct and a class is that by default members in struct are public, but private in class; otherwise, they are functional equivalent. A union can have member functions (including constructors and destructors), but not virtual functions. A union shall not have base classes. A union shall not be used as a base class.
Union ABC obj1(); //Call constructor?
No, This does not call a constructor
union ABC obj1()
means you declare a function with name obj1
and returns an object of union ABC
You have syntax errors in both cases, you have to do the following:
union ABC { ABC() {}; int x; }A, B, C; //You cannot miss this ;
You can do:
typedef union ABC ABCUnion; then ABCUnion A, B,C;
It is the same as
union ABC A, B,C;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.