Can constructor Initializer fields be called with class objects, c++ - c++

I have two classes, one "bank" and one "account". Account's constructor takes an int and a string. Bank is supposed to have two objects of type "account" in it. Is it possible to have the two "account" objects in the fields initializer list be allocated dynamically and not with static values?
Here is the code I have that allocates it statically
class Bank
{
public:
Bank():checkings( 500, "C"), saving( 300, "s"){} //predfined int and string
private:
Account checkings;
Account saving;
};
Is it possible to do this? I want the constuctor to have its fields allocated dynamically according to user input. I keep getting errors so I am unsure if my syntax is wrong.
class Bank
{
public:
Bank():checkings( int val, string s), saving( int val, string s){} //dynamic
private:
Account checkings;
Account saving;
};
Also, how do I call this type of constructor in the .cpp file?

You can't put declarations (like int val) in a member initializer, only expressions (which can be/include previously declared variables).
It looks like maybe you want:
class Bank
{
public:
Bank(int val, std::string s) : checkings(val, s), saving(val, s) {}
// ...
};
or:
class Bank
{
public:
Bank(int check_val, std::string check_s,
int sav_val, std::string sav_s) :
checking(check_val, check_s), saving(sav_val, sav_s) {}
// ...
};

Related

C++ Struct with default argument, optionally changeable in constructor

Let's say I have the following struct.
struct vehicle
{
int price;
char* year;
char* type;
}
I would like to make a regular constructor for it, that would allow me to specify each member.
Nevertheless, I would like to set the member "type", as "car" by default, having only to specify the "type" in the constructor, in the not so often cases when the vehicle would not be a "car".
First of all, you didn't say it, but I sense a small misunderstanding: The difference between a struct and a class is just convention. Structs are classes in C++. The keywords struct and class can be used to declare a class and the only difference is the default access (in accordance with the common convention that structs have all public).
That out of the way, you can simply write two constructors (i am using std::string for strings, because I find c-strings extremely difficult to work with):
struct vehicle
{
int price;
std::string year;
std::string type;
vehicle(int p, const std::string& y, const std::string& t) : price(p),year(y),type(t) {}
vehicle(int p, const std::string& y) : price(p),year(y),type("car") {}
};
You can also use in class initializer (they came with C++11):
struct vehicle
{
int price;
std::string year;
std::string type{"car"};
vehicle(int p, const std::string& y, const std::string& t) : price(p),year(y),type(t) {}
vehicle(int p, const std::string& y) : price(p),year(y) {}
};
The initializer list on the constructor wins over the in class initializer, and in the second constructor the in class initializer is used.

C++ Declaring an inherited constructor?

I'm having difficulties in defining a constructor for a class that inherits the properties of another class
class Transportation {
public:
int ID;
string company;
string vehicleOperator;
Transportation(int,string,string) {
}
};
class SeaTransport: public Transportation {
public:
int portNumber;
SeaTransport(int)::Transportation(int,string,string) {
}
};
I'm having issues with line 18 (SeaTransport(int)::Transportation(int,string,string)).
The error I receive occurs at the pont where I declare Transportation.
As seen in the code, a class Transportation is the body class and class SeaTransport inherits the properies of Transportation.
Transportation::Transportation(int, std::string, std::string)
+2 overloads
type name is not allowed
This error occurs at the int
typedef std::__cxx11::basic_string std::string
type name is not allowed
and this final error occurs at both string variables.
It seems you mix together scoping and a constructor initializer list.
The double-colon operator :: is for scope, while a constructor followed by a single colon and a list of initializations is an initializer list.
You must declare the SeaTransport constructor to take all the arguments, including those for the parent class (assuming you want to pass them on to the base constructor):
SeaTransport(int port, int id, string company, string operator);
Then in the definition (implementation) of the constructor you "call" the parent constructor in the constructor initializer list:
SeaTransport(int port, int id, string company, string oper)
: Transport(id, company, oper), // "Call" the parent class constructor
portNumber(port) // Initialize the own members
{
}
As Mr Some Programmer Dude said, you've a Scope problem in your code,
I will try to answer for your second question which is, how to add featured variables on your constructor.
Same as what you did for the port attribute.
You can define before all your Attribute which is boatNumber as int boadNumber = 0 then, you'll overload your
constructor with boatNumber(num) after the initializer operator and int num before the initializer operator.
class Transportation {
public:
int ID;
string company;
string vehicleOperator;
Transportation(int,string,string) {
}
~Transportation(){}
};
class SeaTransport: public Transportation {
public:
int portNumber;
int boatNumber;
SeaTransport(int num, int port, int id, string company, string oper)
:Transportation(id, company, oper), boatNumber(num),portNumber(port) {}
~SeaTransport(){}
};
But, if you want to get things more specific, you can create another class which is derived from SeaTransport
And then you'll define the number of your boat and more other details, if you want.
I'll draw you an instance of it :
class Boat: public SeaTransport {
public:
int boatNumber;
Boat(int bNum,int num, int port, int id, string company, string oper):
SeaTransport( num, port, id, company, oper),boatNumber(bNum){}
~Boat(){}
};

How is a constructor for a derived class supposed to be like in c++ when derived class has added data member

I am new to c++. I have been trying to get past this error. I know when a class in derived, it inherits everything from the base class, but what if the derived class has other data members? How is the constructor suppose to be?
When I try putting only the new I try to pass parameters to the newly made class members in the constructor I get an error to say it doesn't match that of the base class. When I try using that of the base class and adding the new data members it tells me I am redefining. So I wonder whats left to do to get past this error below is my code.
This is the base class:
class movielibrarybase
{
public:
movielibrarybase(string name, string dirname, string gen, int price);
void setname(string name);
string getname();
void setdirector_name(string dirname);
string getdirector_name();
void setgenre(string gen);
string getgenre();
void setprice(int price);
int getprice();
void display();
~movielibrarybase();
protected:
string name;
string director_name;
string genre;
int price;
};
And this is the derived class:
class songlibrary: public movielibrarybase
{
public:
songlibrary();
void setartist_name(string name);
string getartist_name();
void setsong_position(string position);
string getsong_position;
~songlibrary();
protected:
string artist_name;
string song_postion;
};
I am getting the following errors:
songlibrary.cpp||In constructor 'songlibrary::songlibrary(std::string, std::string, std::string, int, std::string, std::string)':|
songlibrary.cpp|6|error: no matching function for call to 'movielibrarybase::movielibrarybase()'|
movielibrarybase.cpp|3|note: candidates are: movielibrarybase::movielibrarybase(std::string, std::string, std::string, int)|
movielibrarybase.h|8|note: movielibrarybase::movielibrarybase(const movielibrarybase&)|
songlibrary.cpp|34|error: no 'std::string songlibrary::getsong_position()' member function declared in class 'songlibrary'|
For that case you use the member initializer list in the constructor to invoke the right constructor in the base class:
songlibrary::songlibrary(string name, string dirname, string gen, int price,
string artist_name, string song_position)
: movielibrarybase(name, dirname, gen, price), // initialize base class
artist_name(artist_name), // initialize member in this class
song_position(song_position) {
// other ctor stuff
}
If you do not state the parent class on that list, it will default to the default constructor. Since there is no default constructor in your movielibrarybase class, a compiler error occurred.
In your case it would be something like:-
songlibrary::songlibrary( string n, string director, string gen,
int pri, string artist, string song )
: movielibrarybase( n, director, gen, pri ),
artist_name( artist ), song_postion( song )
One thing to note here is sequence in member initializer list matters. First calls should be to base classes and then derived classes members should be initialized in the order in which they are declared in a class.
Also, class members are initialized in the order of their declaration in the class, the order in which they are listed in a member initialization list makes not a whit of difference

C++ calling multiple constructors

I am trying to accomplish the following: I have 4 classes(lets call one primary, other 3 secondary ones) within one namespace, I want to store instances of secondary classes as private members of primary, to do this I need to call secondary constructors from primary's one and then store instances. But Unfortunately I do not completely understand how to do it (not really experienced with c++): here is what I have in header file:
class secondary_one
{
private:
int number1;
public:
secondary_one(int);
int get_number1() const;
};
class secondary_two
{
private:
int number2;
public:
secondary_two(int);
int get_number2() const;
};
class secondary_three
{
private:
int number3;
public:
secondary_three(int);
int get_number3() const;
};
And 'primary' class is:
class primary
{
private:
secondary_one one;
secondary_two two;
secondary_three three;
public:
primary(int,int,int);
};
Upon calling primary constructor I want first argument to be send to constructor of secondary_one, second argument to constructor of secondary_two and so on.
And then store instances as private members. Is it even possible or I am just wasting time? If it is, can you give a short example what should I have in header and source file?
Use the constructor initialization list:
class primary
{
public:
primary(int a, int b, int c) : one(a), two(b), three(c) {}
private:
secondary_one one;
secondary_two two;
secondary_three three;
};

creation of an object in another class(without inheritance)

Hi everybody=) the problem: Compilier can't executed a constructor of class oper because there is no default constructors in class person.
text of error:
'person' : no appropriate default constructor available
the question is: How I can solve this problem without creating default constructors and without inheritance.
here is the code of class person:
class person:public gsm
{
public:
string name,tel;
int tax;
public:
person(string m);
person(string m,string t,string n,int a);
void input(string n, string t, int tx);
void output();
person& operator=(person& a);
bool operator==(person& a);
bool operator!=(person& a);
};
and this is class operator:
class oper
{
private:
person b[10];
int mid_tax1,mid_tax2;
public:
oper();
void set_t1(int tax);
void set_t2(int tax);
void count();
void add_person(person a,int i);
void out();
};
constructor of class oper:
oper::oper()
{
this->mid_tax1=0;
this->mid_tax2=0;
for(int i=0;i<10;i++)
{
b[i].tel="";
b[i].name="";
b[i].tax=0;
}
}
class oper contains 10 instances of person. To build oper you have to build the 10 instances.
When you are in the constructor of oper::oper you are after the class and its contents were constructed. Since there is no default constructor for person there is no way for the compiler to build oper.
Why aren't you allowed to use a default constructor?
Why are you creating a fixed array of 10 people and then support a function called add_person? Is the number of people fixed or dynamic?
If you are using C++03 / C++11 you can use initializer lists to pass the values to the Ctor of person during construction. But it will not be a pretty piece of code.
oper::oper()
: b({""},{""} .... ), mid_tax1(0), mid_tax2(0)
{
...
}
The correct solution is either adding a default constructor or moving away from a fixed array of 10 persons to a dynamic container of N persons
use std::list instead of the array.