-4

I want a clarification

struct Sphere
{
    int a;

    Sphere()  {}
    Sphere(int given)
    {
        a = given;
    }

    Sphere (const Sphere &s)
    {
        a=s.a;
    }
};

When I do this :

 Sphere mySphere;
 mySphere.a = 5;

Which constructor is being called? What is the role of const here? If I omit the const constructor, then value of a isn't assigned. Why is that?

afsara_ben
  • 542
  • 1
  • 11
  • 30
  • 1
    `Sphere mySphere;` invoke the default constructor and `mySphere.a = 5;` invoke nothing but assign a value to the a member. – Adrien Givry Jul 26 '19 at 12:12
  • `Sphere mySphere;` default constructs the object `mySphere`. The little code you show doesn't use the conversion constructor or the copy constructor. As for why the `const` (in the copy constructor I assume you mean) please [get a couple of good books and read](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282). – Some programmer dude Jul 26 '19 at 12:12
  • There is no language CPP/C. Are you mixing languages? The C language doesn't have destructors. – Thomas Matthews Jul 26 '19 at 14:00
  • @ThomasMatthews wow didn't know that – afsara_ben Jul 26 '19 at 14:06

1 Answers1

2

Which constructor is being called?

The default constructor.

What is the role of const here?

None whatsoever.

If I omit the const constructor, then value of a isn't assigned. Why is that?

I don't know and that doesn't make sense.

You're not using the copy constructor. At all.

All you're doing is default-constructing a Sphere then assigning to its data member.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055