0

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;
}
Renz Carillo
  • 349
  • 2
  • 11

1 Answers1

3

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);
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • how about when calling obj, when i used printf("%d",obj,"\n"); the result was referring to the first data member which is equivalent to 'obj.a', but then i assigned int b = obj and it's not working? – Renz Carillo Apr 28 '21 at 06:40
  • @RenzCarillo I suggest you look at the topic of uniform initialization as well.[List initialization](https://en.cppreference.com/w/cpp/language/list_initialization) – east1000 Apr 28 '21 at 06:42
  • @RenzCarillo `printf("%d",obj,"\n")` is wrong on many levels. The first being that `obj` can't be used like a value when passing it to a C function. If the compiler doesn't give you errors for that, then it might have non-standard and non-portable extensions that allow it. To use the value of `obj.a` (in `printf`, initializations, or otherwise) you ***must*** explicitly use the member `obj.a`. – Some programmer dude Apr 28 '21 at 06:45