C++ Constructor

Default constructor in C

You can create initializer functions that take a pointer to a structure. This was common practice.

Also functions that create a struct and initialize it (like a factory) - so there is never a time where the struct is "uninitialized" in the "client" code. Of course - that assumes people follow the convention and use the "constructor"/factory...

horrible pseudo code with NO error checking on malloc or free

somestruct* somestruct_factory(/* per haps some initializer agrs? */)
{
malloc some stuff
fill in some stuff
return pointer to malloced stuff
}

void somestruct_destructor(somestruct*)
{
do cleanup stuff and also free pointer
free(somestruct);
}

Someone will probably come along and explain how some early C++ preprocessors/compilers worked to do this all in C.

C equivalent of new Object(constructor)

The equivalent (or replacement) of a constructor in C is an initializer. You can use such an initializer in the construction of a compound literal (another C speciality) and by that initialize your new object by assignment.

MyClass* ptr = malloc(sizeof *ptr);
*ptr = (MyClass){ .a = 1, .b = 34 };

a convention to do so systematically could be to always have an "init" function

inline
MyClass* MyClass_init(MyClass* ptr, T1 arg1, T2 arg2) {
if (ptr) {
*ptr = (MyClass){ .a = arg1, .b = arg2, };
}
return ptr;
}

and then to call that at initialization of the pointer

MyClass* ptr = MyClass_init(malloc(sizeof *ptr), arg1,arg2);

Constructor for structs in C

In C I typically create a function in the style of a constructor which does this. For example (error checking omitted for brevity)

Object* Object_new(int id, int value) { 
Object* p = malloc(sizeof(Object));
p->id = id;
p->value = value;
return p;
}

...
Object* p1 = Object_new(id++, myValue);

Can constructor call another constructor in c++?

Not before C++11.

Extract the common functionality into a separate function instead. I usually name this function construct().

The "so-called" second call would compile, but has a different meaning in C++: it would construct a new object, a temporary, which will then be instantly deleted at the end of the statement. So, no.

A destructor, however, can be called without a problem.

Need help understanding the constructor in my program (c++)

A constructor is a member function of a class that initializes objects of a class. In C++, Constructor is automatically called when an object(instance of a class) create. It is a special member function of the class.
How constructors are different from a normal member function?

A constructor is different from normal functions in the following ways:

  • Constructor has the same name as the class itself
  • Constructors don’t have a return type
  • A constructor is automatically called when an object is created.
  • If we do not specify a constructor, C++ compiler generates a default constructor for us (expects no parameters and has an empty body).

Furthermore, in the definition of a constructor of a class, the member initializer list specifies the initializers for direct and virtual bases and non-static data members. (Not to be confused with std::initializer_list.)

A default constructor does not have any parameter, but if you need, a constructor can have parameters. This helps you to assign an initial value to an object at the time of its creation.

There is also the copy constructor, but I'm sure that with a good C++ book as @NathanOliver said, you will be able to go deeper on this and other things too.
There is a special type of Constructors that takes an object as an argument and is used to copy values of data members of one object into another object.

#include <iostream>
#include <string>

class Vertebrae { // here i am declaring my class as Vertebrae
private: // here i am setting a private access modifier
std::string brain; // creating the string brain as a private attribute
std::string backbone; // creating the string backbone as a private attribute
std::string skeleton; // creating the string skeleton as a private attribute

public: //setting my public access modifier

void setBrain(std::string a) {
brain = a;
}

std::string getBrain() {
return brain;
}

void setBackbone(std::string b) {
backbone = b;
}

std::string getBackbone(){
return backbone;
}

void setSkeleton(std::string c) {
skeleton = c;
}

std::string getSkeleton() {
return skeleton;
}

// Default Constructor Example
Vertebrae() {
// Object initialization and other stuff eventually
}

// Parametrized Constructor Example
Vertebrae(std::string brain, std::string backbone, std::string skeleton) {
// Or use setMethod(...)
this->brain = brain;
this->backbone = backbone;
this->skeleton = skeleton;
}

/*
// Constructor with Member Initializer List
Vertebrae(std::string brain, std::string backbone, std::string skeleton) : brain(brain), backbone(backbone), skeleton(skeleton) {
// Other stuff eventually only
}

*/

};

int main(){
Vertebrae A;
Vertebrae B;
Vertebrae C;
A.setBrain("Brains");
B.setBackbone("Spines");
C.setSkeleton("Boney Skeletons");

std::cout << "Vertebrates have " << A.getBrain(); //outputting the first definition of a vertebrae
std::cout << ", "; //outputting a comma
std::cout << B.getBackbone(); //outputting the second definition of a vertebrae
std::cout << ", and "; //outputting another comma and the word and
std::cout << C.getSkeleton(); //outputting the third definition of a vertebrae
std::cout << "\n";
return 0;
}

Just some tips:

  • Pay attention to private and public methods that can be accessed outside the classes (I'm talking about your "setters" methods).
  • Use std and do not specify "using namespace std" (Check here: Why is “using namespace std;” considered bad practice?

That's all. I hope that this was helpful.
Cheers, Denny

Create constructor in C

You could create an Animal instance containing the default values and then use that to initialize your other instances.

Example:

animal.h

typedef struct Animal Animal;
struct Animal {
// ...
};

extern const Animal animal;

animal.c

const Animal animal = {.construct = Animal_construct};

Then, in main.c

int main(void) {
Animal dog = animal; // Creating a dog instance from `animal`
dog.construct(&dog, "Doge", 8); //Constructing dog...
// ...
}

Default initialization explicit constructor c++

Your use is okay. The worst thing that could happen would be that the compiler would not be able to use the constructor since it is explicit and fail to compile. However, defining a variable as you have will correctly call the explicit default constructor.

The use of explicit for a default constructor prevents uses like the following:

Foo some_fn() {
return {}; // Fails as the default constructor is explicit.
return Foo{}; // OK
}


Related Topics



Leave a reply



Submit