Struct Constructor in C++?

Can a struct have a constructor in C++?

I have been trying to solve this problem but I am not getting the syntax.

Incompatible implicit declaration of built-in function ‘malloc’

I'm getting this error:

warning: incompatible implicit declaration of built-in function ‘malloc’

I am trying to do this:

fileinfo_list* tempList = malloc(sizeof(fileinfo_list));

Just for the reference the struct used at hand is:

typedef struct {
    fileinfo** filedata;
    size_t nFiles;
    size_t size;
    size_t fileblock;
} fileinfo_list;

I don't see anything wrong with what I've done. I'm just creating a tempList with the size of 1 x fileinfo_list.

What are the differences between struct and class in C++?

This question was already asked in the context of C#/.Net.

Now I'd like to learn the differences between a struct and a class in C++. Please discuss the technical differences as well as reasons for choosing one or the other in OO design.

I'll start with an obvious difference:

  • If you don't specify public: or private:, members of a struct are public by default; members of a class are private by default.

I'm sure there are other differences to be found in the obscure corners of the C++ specification.

How to print struct variables in console?

How can I print (to the console) the Id, Title, Name, etc. of this struct in Golang?

type Project struct {
    Id      int64   `json:"project_id"`
    Title   string  `json:"title"`
    Name    string  `json:"name"`
    Data    Data    `json:"data"`
    Commits Commits `json:"commits"`
When should I use Struct vs. OpenStruct?

In general, what are the advantages and disadvantages of using an OpenStruct as compared to a Struct? What type of general use-cases would fit each of these?

Error: "Cannot modify the return value" c#

I'm using auto-implemented properties. I guess the fastest way to fix following is to declare my own backing variable?

public Point Origin { get; set; }

Origin.X = 10; // fails with CS1612

Error Message: Cannot modify the return value of 'expression' because it is not a variable

An attempt was made to modify a value type that was the result of an intermediate expression. Because the value is not persisted, the value will be unchanged.

To resolve this error, store the result of the expression in an intermediate value, or use a reference type for the intermediate expression.

Are there any downsides to passing structs by value in C, rather than passing a pointer?

Are there any downsides to passing structs by value in C, rather than passing a pointer?

If the struct is large, there is obviously the performance aspect of copying lots of data, but for a smaller struct, it should basically be the same as passing several values to a function.

It is maybe even more interesting when used as return values. C only has single return values from functions, but you often need several. So a simple solution is to put them in a struct and return that.

Are there any reasons for or against this?

Since it might not be obvious to everyone what I'm talking about here, I'll give a simple example.

If you're programming in C, you'll sooner or later start writing functions that look like this:

void examine_data(const char *ptr, size_t len)

char *p = ...;
size_t l = ...;
examine_data(p, l);

This isn't a problem. The only issue is that you have to agree with your coworker in which the order the parameters should be so you use the same convention in all functions.

But what happens when you want to return the same kind of information? You typically get something like this:

char *get_data(size_t *len);
    *len = ...datalen...;
size_t len;
char *p = get_data(&len);

This works fine, but is much more problematic. A return value is a return value, except that in this implementation it isn't. There is no way to tell from the above that the function get_data isn't allowed to look at what len points to. And there is nothing that makes the compiler check that a value is actually returned through that pointer. So next month, when someone else modifies the code without understanding it properly (because he didn't read the documentation?) it gets broken without anyone noticing, or it starts crashing randomly.

So, the solution I propose is the simple struct

struct blob { char *ptr; size_t len; }

The examples can be rewritten like this:

void examine_data(const struct blob data)
    ... use and data.len ...

struct blob = { .ptr = ..., .len = ... };

struct blob get_data(void);
    return (struct blob){ .ptr =, .len = ...len... };
struct blob data = get_data();

For some reason, I think that most people would instinctively make examine_data take a pointer to a struct blob, but I don't see why. It still gets a pointer and an integer, it's just much clearer that they go together. And in the get_data case it is impossible to mess up in the way I described before, since there is no input value for the length, and there must be a returned length.

Difference between a Structure and a Union

Is there any good example to give the difference between a struct and a union? Basically I know that struct uses all the memory of its member and union uses the largest members memory space. Is there any other OS level difference?

How do I do a literal *int64 in Go?

I have a struct type with a *int64 field.

type SomeType struct {
    SomeField *int64

At some point in my code, I want to declare a literal of this (say, when I know said value should be 0, or pointing to a 0, you know what I mean)

instance := SomeType{
    SomeField: &0,

...except this doesn't work

./main.go:xx: cannot use &0 (type *int) as type *int64 in field value

So I try this

instance := SomeType{
    SomeField: &int64(0),

...but this also doesn't work

./main.go:xx: cannot take the address of int64(0)

How do I do this? The only solution I can come up with is using a placeholder variable

var placeholder int64
placeholder = 0

instance := SomeType{
    SomeField: &placeholder,

Note: the &0 syntax works fine when it's a *int instead of an *int64. Edit: no it does not. Sorry about this.


Aparently there was too much ambiguity to my question. I'm looking for a way to literally state a *int64. This could be used inside a constructor, or to state literal struct values, or even as arguments to other functions. But helper functions or using a different type are not solutions I'm looking for.

C-like structures in Python

Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:

class MyStruct():
    def __init__(self, field1, field2, field3):
        self.field1 = field1
        self.field2 = field2
        self.field3 = field3
Why should we typedef a struct so often in C?

I have seen many programs consisting of structures like the one below

typedef struct 
    int i;
    char k;
} elem;

elem user;

Why is it needed so often? Any specific reason or applicable area?

What are the use(s) for struct tags in Go?

In the Go Language Specification, it mentions a brief overview of tags:

A field declaration may be followed by an optional string literal tag, which becomes an attribute for all the fields in the corresponding field declaration. The tags are made visible through a reflection interface but are otherwise ignored.

// A struct corresponding to the TimeStamp protocol buffer.
// The tag strings define the protocol buffer field numbers.
struct {
  microsec  uint64 "field 1"
  serverIP6 uint64 "field 2"
  process   string "field 3"

This is a very short explanation IMO, and I was wondering if anyone could provide me with what use these tags would be?

Difference between 'struct' and 'typedef struct' in C++?

In C++, is there any difference between:

struct Foo { ... };


typedef struct { ... } Foo;
Struct like objects in Java

Is it completely against the Java way to create struct like objects?

class SomeData1 {
    public int x;
    public int y;

I can see a class with accessors and mutators being more Java like.

class SomeData2 {
    int getX();
    void setX(int x);

    int getY();
    void setY(int y);

    private int x;
    private int y;

The class from the first example is notationally convenient.

// a function in a class
public int f(SomeData1 d) {
    return (3 * d.x) / d.y;

This is not as convenient.

// a function in a class
public int f(SomeData2 d) {
    return (3 * d.getX()) / d.getY();
How to initialize a struct in accordance with C programming language standards

I want to initialize a struct element, split in declaration and initialization. This is what I have:

typedef struct MY_TYPE {
  bool flag;
  short int value;
  double stuff;

void function(void) {
  MY_TYPE a;
  a = { true, 15, 0.123 }

Is this the way to declare and initialize a local variable of MY_TYPE in accordance with C programming language standards (C89, C90, C99, C11, etc.)? Or is there anything better or at least working?

Update I ended up having a static initialization element where I set every subelement according to my needs.

How to check for an empty struct?

I define a struct ...

type Session struct {
    playerId string
    beehive string
    timestamp time.Time

Sometimes I assign an empty session to it (because nil is not possible)

session = Session{};

Then I want to check, if it is empty:

if session == Session{} {
     // do stuff...

Obviously this is not working. How do I write it?

Why Choose Struct Over Class?

Playing around with Swift, coming from a Java background, why would you want to choose a Struct instead of a Class? Seems like they are the same thing, with a Struct offering less functionality. Why choose it then?

When should you use a class vs a struct in C++?

In what scenarios is it better to use a struct vs a class in C++?

What's the difference between struct and class in .NET?

What's the difference between struct and class in .NET?

How to define multiple name tags in a struct

I need to get an item from a mongo database, so I defined a struct like this

type Page struct {
    PageId string                 `bson:"pageId"`
    Meta   map[string]interface{} `bson:"meta"`

Now I also need to encode it to JSON, but it encodes the fields as uppercase (i get PageId instead of pageId) so i also need to define field tags for JSON. I tried something like this but it didn't work:

type Page struct {
    PageId string                 `bson:"pageId",json:"pageId"`
    Meta   map[string]interface{} `bson:"meta",json:"pageId"`

So how can this be done, define multiple name tags in a struct?

typedef struct vs struct definitions

I'm a beginner in C programming, but I was wondering what's the difference between using typedef when defining a structure versus not using typedef. It seems to me like there's really no difference, they accomplish the same goal.

struct myStruct{
    int one;
    int two;


typedef struct{
    int one;
    int two;
Struct inheritance in C++

Can a struct be inherited in C++?

When should I use a struct rather than a class in C#?

When should you use struct and not class in C#? My conceptual model is that structs are used in times when the item is merely a collection of value types. A way to logically hold them all together into a cohesive whole.

I came across these rules here:

  • A struct should represent a single value.
  • A struct should have a memory footprint less than 16 bytes.
  • A struct should not be changed after creation.

Do these rules work? What does a struct mean semantically?

How to set default values in Go structs

There are multiple answers/techniques to the below question:

  1. How to set default values to golang structs?
  2. How to initialize structs in golang

I have a couple of answers but further discussion is required.

Why are mutable structs “evil”?

Following the discussions here on SO I already read several times the remark that mutable structs are “evil” (like in the answer to this question).

What's the actual problem with mutability and structs in C#?

How do you compare structs for equality in C?

How do you compare two instances of structs for equality in standard C?

Why isn't sizeof for a struct equal to the sum of sizeof of each member?

Why does the sizeof operator return a size larger for a structure than the total sizes of the structure's members?

Structure padding and packing


struct mystruct_A
   char a;
   int b;
   char c;
} x;

struct mystruct_B
   int b;
   char a;
} y;

The sizes of the structures are 12 and 8 respectively.

Are these structures padded or packed?

When does padding or packing take place?

C++ Structure Initialization

Is it possible to initialize structs in C++ as indicated below:

struct address {
    int street_no;
    char *street_name;
    char *city;
    char *prov;
    char *postal_code;

address temp_address = { .city = "Hamilton", .prov = "Ontario" };

The links here and here mention that it is possible to use this style only in C. If so why is this not possible in C++? Is there any underlying technical reason why it is not implemented in C++, or is it bad practice to use this style. I like using this way of initializing because my struct is big and this style gives me clear readability of what value is assigned to which member.

Please share with me if there are other ways through which we can achieve the same readability.

I have referred the following links before posting this question:

  1. C/C++ for AIX
  2. C Structure Initialization with Variable
  3. Static structure initialization with tags in C++
  4. C++11 Proper Structure Initialization
Why can't I define a default constructor for a struct in .NET?

In .NET, a value type (C# struct) can't have a constructor with no parameters. According to this post this is mandated by the CLI specification. What happens is that for every value-type a default constructor is created (by the compiler?) which initialized all members to zero (or null).

Why is it disallowed to define such a default constructor?

One trivial use is for rational numbers:

public struct Rational {
    private long numerator;
    private long denominator;

    public Rational(long num, long denom)
    { /* Todo: Find GCD etc. */ }

    public Rational(long num)
        numerator = num;
        denominator = 1;

    public Rational() // This is not allowed
        numerator = 0;
        denominator = 1;

Using current version of C#, a default Rational is 0/0 which is not so cool.

PS: Will default parameters help solve this for C# 4.0 or will the CLR-defined default constructor be called?

Jon Skeet answered:

To use your example, what would you want to happen when someone did:

 Rational[] fractions = new Rational[1000];

Should it run through your constructor 1000 times?

Sure it should, that's why I wrote the default constructor in the first place. The CLR should use the default zeroing constructor when no explicit default constructor is defined; that way you only pay for what you use. Then if I want a container of 1000 non-default Rationals (and want to optimize away the 1000 constructions) I will use a List<Rational> rather than an array.

This reason, in my mind, is not strong enough to prevent definition of a default constructor.