I was (once again) experimenting with some CPP code using constructors. I defined a constuctors 2 different ways. I believe the end result is the same, but what causes the difference in run-time for the program. Specifically, the first code took my computer 9 seconds to run, while the second code took 15 seconds, a 66% difference. I repeated the "experiment" several times and got the same result. I'm guessing that the first code doesn't have to create objects a,b,c and then initialize them to a value, but it does both at the same time? (i.e.) they are created with the values given.
Can you guys explain the difference? Is the first more "efficient"? Are there any downsides to writing a constructor like this?
Expand|Select|Wrap|Line Numbers
- #include<iostream>
- using namespace std;
- class trial{
- private:
- double a,b,c;
- public:
- trial();
- void display();
- };
- trial::trial()
- : a(5), b(9) , c(10)
- { }
- void trial::display(){
- cout<<a<<' '<<b<<' '<<c;
- }
- int main(){
- for(unsigned long long int i=0; i<990000000; i++){
- trial f;
- }
- return 0;
- }
Expand|Select|Wrap|Line Numbers
- #include<iostream>
- using namespace std;
- class trial{
- private:
- double a,b,c;
- public:
- trial();
- void display();
- };
- trial::trial()
- {a=5;
- b=0;
- c=10; }
- void trial::display(){
- cout<<a<<' '<<b<<' '<<c;
- }
- int main(){
- for(unsigned long long int i=0; i<990000000; i++){
- trial f;
- }
- return 0;
- }