Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ structures and constructors

Tags:

c++

structure

A quick question about structures in C++ that I haven't managed to find the answer for:

I've read that the only difference between structures and classes is the member-visibility. So, does the compiler give the structure a default constructor? (and a default copyconstructor, destructor, and assignment operator aswell?) And can you define all of the above yourself?

Thanks, István

like image 598
István Kohn Avatar asked Jun 20 '11 14:06

István Kohn


People also ask

Do C structures have constructors?

3. Constructor creation in structure: Structures in C cannot have a constructor inside a structure but Structures in C++ can have Constructor creation.

What is constructor structure?

Constructors are a feature of C++ (but not C) that make initialization of structures convenient. Within a structure type definition, define a constructor in a way that is similar to a function definition, with the following differences. The name of the constructor must be the same as the name of the structure type.

What is a constructor in C?

Constructor in C++ is a special method that is invoked automatically at the time of object creation. It is used to initialize the data members of new objects generally. The constructor in C++ has the same name as the class or structure. Constructor is invoked at the time of object creation.

Do I need a constructor for a struct?

Technically, a struct is like a class , so technically a struct would naturally benefit from having constructors and methods, like a class does.


1 Answers

Yes, it does, and yes, you can.

like image 74
Andy Thomas Avatar answered Sep 30 '22 02:09

Andy Thomas