What I'm trying do?
I am trying to get user input in the default constructor of the object and compare it in the copy constructor if the previous object and the current object have the same brand name.
What is the problem?
I am not able to call the default and copy constructor of the same object.
My Code:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
class Scooty {
int cc ;
string model, brand;
bool goodBrands();
public:
Scooty () : cc(0), model(""), brand("") {
cout << "\n Enter the following scooty details: \n\n";
cout << "\n \t Brand: ";
cin >> brand;
transform(brand.begin(), brand.end(), brand.begin(), :: tolower);
cout << "\n \t Model: ";
cin >> model;
transform(model.begin(), model.end(), model.begin(), :: tolower);
cout << "\n \t CC: ";
cin >> cc;
}
Scooty (Scooty &s) { if (brand == s.brand) cout << "You will get a discount!\n"; }
void computeDataAndPrint ();
};
bool Scooty :: goodBrands() {
if (brand == "honda" || brand == "tvs" || brand == "yamaha")
return true;
return false;
}
void Scooty :: computeDataAndPrint () {
if (cc > 109 && goodBrands())
cout << "\n Good Choice!\n";
else
cout << "\n Its okay!\n";
}
int main() {
Scooty s;
Scooty s1, s1(s) // This gives error
s.computeDataAndPrint();
return 0;
}
C++11 introduces the concept of delegating constructors. A constructor can call another constructor of the same class in its own initialization list. For example:
Scooty (const Scooty &s)
: Scooty() // <-- add this
{
if (brand == s.brand)
cout << "You will get a discount!\n";
}
This allows a constructor to leverage the initialization(s) performed by another constructor of the same class.
In earlier versions of C++, the initialization list can only call the constructor of immediate base class(es) and data members, so common initializations must be performed in a separate function/method that the constructor bodies can call as needed. For example:
class Scooty {
int cc;
string model;
string brand;
void init() {
cout << "\n Enter the following scooty details:- \n\n";
cout << "\n \t Brand:";
cin >> brand;
transform(brand.begin(), brand.end(), brand.begin(), ::tolower);
cout << "\n \t Model:";
cin >> model;
transform(model.begin(), model.end(), model.begin(), ::tolower);
cout << "\n \t CC:";
cin >> cc;
}
...
public:
Scooty () : cc(0) {
init(); // <-- here
}
Scooty (const Scooty &s) : cc(0) {
init(); // <-- here
if (brand == s.brand)
cout << "You will get a discount!\n";
}
...
};
int main() {
Scooty s;
Scooty s1(s);
...
return 0;
}