I got compile errors "cannot convert.."
, `"no instance of constructor..". I can't get what I did wrong. I tried to change the way of initialization of an object but it didn't help. Want to understand this better.
Error C2440 '': cannot convert from 'const char [11]' to 'Course'
Error C2512 'LectureTitle::LectureTitle': no appropriate default constructor available
Error (active) E0289 no instance of constructor "Course::Course" matches the argument list
Error (active) E0312 no suitable user-defined conversion from "Week" to "LectureTitle" exists
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Specialization {
string data;
explicit Specialization(string& new_value) {
data = new_value;
}
};
struct Course {
string data;
explicit Course(string& new_value) {
data = new_value;
}
};
struct Week {
string data;
explicit Week(string& new_value) {
data = new_value;
}
};
struct LectureTitle {
string specialization;
string course;
string week;
LectureTitle(Specialization& new_value1, Course& new_value2, Week new_value3) {
specialization = new_value1.data;
course = new_value2.data;
week = new_value3.data;
}
};
int main() {
LectureTitle title (
Specialization("C++"),
Course("White belt"),
Week("4th")
);
}
LectureTitle title ( Specialization("C++"), Course("White belt"), Week("4th") );
Here you are trying to create an instance of LectureTitle
with temporary values (rvalues) of Specialization
, Course
and Week
. They are temporary because they are not named variables, i.e. not defined as variables before this piece of code.
All your constructors, however, take named variables references (lvalues). That's why you get the compiler errors. To correct these errors you can make the constructors accept const value references like so:
explicit Specialization(const std::string& new_value) {
data = new_value;
}
explicit Course(const std::string& new_value) {
data = new_value;
}
explicit Week(const std::string& new_value) {
data = new_value;
}
LectureTitle(const Specialization& new_value1, const Course& new_value2, const Week new_value3) {
specialization = new_value1.data;
course = new_value2.data;
week = new_value3.data;
}
Const lvalue references can bind to rvalues - i.e. extend the lifetime of a temporary; and those temporaries can be used to intialise the member variables in your constructors.