Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference between C c; and C c = C();?

#include<iostream>
using namespace std;

class C{
private:
    int value;
public:
    C(){
        value = 0;
        cout<<"default constructor"<<endl;
    }
    C(const C& c){
        value = c.value;
        cout<<"copy constructor"<<endl;
    }
};
int main(){
    C c1;
    C c2 = C();
}

Output:

default constructor

default constructor

Question:

For C c1; default constructor will be called obviously, for C c2 = C(); I thought default constructor will be called to initialize a temporary object, then copy constructor will be call to initialize c2, It seems that I am wrong. why?

like image 767
expoter Avatar asked Mar 08 '16 07:03

expoter


People also ask

Is C+ and C same?

C++ was developed by Bjarne Stroustrup in 1979. C does no support polymorphism, encapsulation, and inheritance which means that C does not support object oriented programming. C++ supports polymorphism, encapsulation, and inheritance because it is an object oriented programming language. C is a subset of C++.

Is C or C+ Better?

Compared to C, C++ has significantly more libraries and functions to use. If you're working with complex software, C++ is a better fit because you have more libraries to rely on. Thinking practically, having knowledge of C++ is often a requirement for a variety of programming roles.

Is C C++ and C# same?

Although they sound alike, C, C++, and C# are different programming languages. Let us understand the difference between two of the most widely used programming languages, C++ and C#.

Is C# and C the same?

C language supports procedural programming. Whereas C# supports object oriented programming.


1 Answers

This is an example of copy elision - basically the compiler is allowed to optimize away the copy. Described here: http://en.cppreference.com/w/cpp/language/copy_elision

like image 139
NexusSquared Avatar answered Oct 04 '22 15:10

NexusSquared