Defining default values in c++ constructor? [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Longtime java programmer here, recently switched to C++ for the first time.
I am trying to have several constructors for a Person class. I have defined Person as follows:
class Person {
private:
//stuff
public:
Person(std::string firstName, std::string lastName, int age);
Person();//I want to define a constructor with no parameters, but NOT a default constructor!
};
My implementation:
#include "Person.h"
Person::Person(std::string firstName, std::string lastName, int age)
: firstName(firstName), lastName(lastName), age(age)
{
}
Person::Person()//no errors here
: firstName("default first"), lastName("default last"), age(0)
{
}
Finally, my main function:
int main() {
Person p1 = Person("Chuck", "Norris", 55)//Variable constructor
Person p2 = Person();//SHOULD invoke no-args constructor
return 0;
}
However, when I attempt to instantiate p2 using the no args constructor, I get the following error:
Expected a ';', which in this context makes no sense. I tried Person p2;, same issue.
How does one call a no-args constructor in C++ with user-defined default values?

You are missing a ; after p1!
int main() {
Person p1 = Person("Chuck", "Norris", 55) <-HERE
Person p2 = Person();//SHOULD invoke no-args constructor
return 0;
}

Related

Passing values to a Constructor which takes pointers parameter [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
I am very new to C++ and I am trying to initialize an object called GameObject, in a class called Room, which holds a gameObjects array. The constructor of the GameObject class takes pointers as the parameters to initialize the fields. But I keep getting the error saying that there is "No matching constructor for initialization of GameObject. Could someone tell me what is my mistake here?
Sorry if this question is formatted badly, I am not used to asking C++ questions with multiple header files and source files. But please also correct me on this.
GameObject
GameObject::GameObject(string* _name, string* _description, char* _keyWord):
name(_name), description(_description), keyWord(_keyWord){
}
Room
//error!, "No matching constructor for initialization..."
gameObjects[0] = new GameObject("knife", "a knife", 'k');
gameObjects[1] = new GameObject("sword", "a sword", 's');
};
Well, you in the GameObject constuctor:
GameObject::GameObject(string* _name, string* _description, char* _keyWord):
name(_name), description(_description), keyWord(_keyWord){}
You are accepting the two strings and a char by pointer. So maybe you meant to accept them by reference instead like this:
GameObject::GameObject(string& _name, string& _description, char _keyWord):
name(_name), description(_description), keyWord(_keyWord){}
Which works fine.
For instance take this program:
#include<iostream>
#include<string>
struct my_obj
{
my_obj(std::string s, std::string s_, char c)
: s__(s), s___(s_), char_(c) {}
std::string s__{};
std::string s___{};
char char_{};
};
struct my_obj_2
{
my_obj(std::string* s, std::string* s_, char* c)
: s__(s), s___(s_), char_(c) {}
std::string s__{};
std::string s___{};
char char_{};
};
int main()
{
my_obj my_obj_1("Hello", "Goodbye", 'C'); // works fine
my_obj_2 m_my_obj_2("Hello", "Goodbye", 'c'); // doesn't work fine
}
(1): This works fine because it finds a matching constructor:
std::string -> std::string
(2): Whereas this doesnt work fine because it is this conversion:
std::string -> std::string*
So in conclusion just remove the pointers on the constructor and if you wanted to you could pass then by & or const & like this
GameObject::GameObject(string& _name, string& _description, char _keyWord):
name(_name), description(_description), keyWord(_keyWord){}

Here is a C++ program where it is showing that my function is out of scope. Can someone please tell me the errors and how to fix them [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 10 months ago.
Improve this question
Question
You have to create a class, named Student, representing the student's details, as mentioned above, and store the data of a student. Create setter and getter functions for each element; that is, the class should at least have following functions:
get_age, set_age
get_first_name, set_first_name
get_last_name, set_last_name
get_standard, set_standard
Also, you have to create another method to_string() which returns the string consisting of the above elements, separated by a comma(,). You can refer to stringstream for this.
code:
#include <iostream>
using namespace std;
class Student{
private:
int age;
string fname;
string lname;
int std;
public:
void set_age(int a){age=a;;}
void set_fname(string f){fname=f;} //fname= first name
void set_lname(string l){lname=l;} //lname= last name
void set_std(int s){std=s;}
void get_age(){
cout<<age<<endl;
}
void get_fname(){
cout<<fname<<endl;
}
void get_lname(){
cout<<lname<<endl;
}
void get_std(){
cout<<std<<endl;
}
void to_string(){
string fl=lname+", "+fname; //fl stand for first and last
cout<<fl;
}
};
int main() {
Student z;
int a,s;
string f,l;
cin>>a;
z.set_age(a);
cin>>f;
z.set_fname(f);
cin>>l;
z.set_lname(l);
cin>>s;
z.set_std(s);
get_age();
to_string();
get_std();
return 0;
}
output
Solution.cpp:52:11: error: ‘get_age’ was not declared in this scope
cout<<get_age();
^~~~~~~
Solution.cpp:52:11: note: suggested alternative: ‘getdate’
cout<<get_age();
^~~~~~~
getdate
Solution.cpp:53:15: error: no matching function for call to ‘to_string()’
to_string();
^
You create one Student instance, z, and call misc. setter member functions on that instance. When you then call the functions to print some of the values you've set, you forgot to tell the compiler which instance you want to print the values for. Since you only have one instance, z, add that before the member functions:
z.get_age();
z.to_string();
z.get_std();
Improvement suggestion: Functions that does not return a value but that prints the value would be better named print-something rather than get-something.

What is the use of a constructor? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I dont exactly get the use of a constructor
For example:
class car
{
public:
string name;
long int price;
int mileage
bool ownedByPlayer;
};
Here, why will I use a constructor like this,
class car
{
public:
string name;
long int price;
int mileage
bool ownedByPlayer;
car()
{
ownedByPlayer = false;
}
};
if I can simply define the variable ownedByPlayer where I have declared it. Like: bool ownedByPlayer = false; ?
In your case there is no need to write the constructor. Actually it is recommended to not write a constructor that does nothing but initialize members with default values. Though the correct way would be to use the member initializer list:
car() : ownedByPlayer(false) {}
And since C++11 you can use a default member initializer instead:
class car {
// ...
bool ownedByPlayer = false;
// ...
};
Sometimes constructors actually need to do something. Consider a car registers itself somewhere after being constructed, then your class could look like this:
class car
{
public:
string name;
long int price;
int mileage;
car(string name,long int price, int mileage) : name(name),price(price),mileage(mileage) {
CarRegistrationFacility::register_car(*this);
}
};
Actually I found it difficult to make up an example for a constructor that does more than initializing members, because thats what constructors do. However, when your constructor does more than that, then that "more" happens in the body of the constructor.

C++ Inheritance of abstract reference members for polymorphism [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I have an abstract class with N protected members:
class Something {
protected:
UINT someVal;
std::vector<SomeType> g_MyVec;
// some virtual abstract methods ...
public:
UINT getSomeVal() { return someVal; }
std::vector<SomeType> GetVec() { return g_MyVec; }
}
class SubClass : public Something {
public:
SubClass() { // no members in this class, all inherited from super
someVal = 5; // this sticks
g_myVec = { .. correct initialization }; // this doesn't stick
}
}
The client of this code does:
Something* s = &SubClass();
s->getSomeVal(); // OK, has 5 in it.
s->GetVec(); // Nada, it returns 0 size, nothing at all... WHY?!
Enlightenment is much appreciated.
You are taking an address of the temporary. It's a UB and incorrect code. Subclass gets destroyed along with the vector after the ;
Correct way to do this would be (Assuming no C++11):
Something* s = new Subclass();
s->getSomeVal(); // OK, has 5 in it.
s->GetVec();
delete s;

Defining constructors in a class that uses pointers (C++) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
Okay, so this is my first question on this site, and I'm fairly new to C++. I am trying to create a class of functions that puts the members of various campus clubs into their respective clubs. I was given this class skeleton to follow, but I'm not sure how to define the three constructors, especially how to use the variables that are inside of the parameters. You can pretty much ignore all of the public functions except the constructors. Any ideas?
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Club
{
public:
Club();
Club(Club &c);
Club(string cname);
void addMember(string name);
void removeMember(string name);
const string getClubName();
void loadClub();
const bool isMember(string name);
const string getAllMembers();
friend Club mergeClubs(Club& c1, Club& c2);
~Club();
private:
string *members;
int numMembers;
string clubName;
};
You have three constructors: the default Club(), the copy constructor Club(Club &c) and a third one Club(string cname).
For the default, you're going to have to decide what all the default values for your private members are.
For the copy constructor, all you need to do is copy everything from &c into your own record. So for instance you can do:
numMembers = c.numMembers ;
For the third one, you have to decide what cname is and what you should do with it.
For the copy constructor, you do have one tricky decision to make. What does it mean to copy string * members; You might think you could just say members= c.members ; but then if the original Club gets resized, the copy will be pointing to invalid memory.
Instead of using an array of strings, just use a vector, then you don't need the "numMembers" either.
class Club
{
public:
...
void addMember(string name) { members.push_back(name); }
void removeMemeber(string name) { members.erase(std::remove(members.begin(), members.end(), name), members.end()); }
...
private:
vector<string> members;
string clubName;
};