Renz Carillo
Renz Carillo

Reputation: 430

What is the difference between these three object initialization

What are the differences with these 3 object initialization and when we are calling an object, what is literally happening?

#include <iostream>

class SampleClass {
    public:
    int a;

    SampleClass (int x) {
        a = x;
    }
};

int main() {
    //are there any differences with these 3 object initialization?
    SampleClass obj = 5;
    SampleClass obj1 = SampleClass(10);
    SampleClass obj2(15);

    printf("%d",obj,"\n"); //why does this work, if obj is referring to the first data member of the class
    //int b = obj; //then why couldn't i do this?
    //std::cout << obj << std::endl; //and why does printf works with obj and cout doesn't?

    return 0;
}

Upvotes: 0

Views: 70

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409482

This initialization reference contains all the information you might need.

From that reference we can get the following information:

SampleClass obj = 5;    // Copy initialization
SampleClass obj1 = SampleClass(10);    // Copy initialization
SampleClass obj2(15);    // Direct initialization

It's easier to realize that the first is copy-initialization if we learn that the compiler will treat it as:

SampleClass obj = SampleClass(5);

Upvotes: 3

Related Questions