What is the use of a constructor? [closed] - c++

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.

Related

error: no matching constructor for initialization of 'Card' [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 5 days ago.
Improve this question
So, the title is the error code that I get, and I am not experienced enough to see where the problem lies. I have quite a bit of code here that I would love to get some help with too, see where the problem lies.
main.cpp - the rest of the main code is as usual, so nothing wrong underneath the photo
card.cpp
card.h - part one
card.h - part two
cardDeck.h
cardDeck.cpp
I don't really know what to do here, but I have tried to see if I have any sort of syntax errors.
The compiler is complaining that it can't construct a Card object. There are only 2 places in your code where a Card object is being constructed:
In main(). You are constructing a Card object correctly. So this is not the problem.
In CardDeck's constructor. You are constructing 52 default Card objects in your cardVector (this is the problem!), and then replacing them with new Cards in a loop.
The replacement Cards are being constructed correctly. However, cardVector.resize() requires Card to be default-constructible when adding new elements to the vector. But Card is not default-constructible, because it has only 1 user-defined constructor which requires a Suit and a Rank as input (thus the compiler-generated default constructor is disabled), and you are not providing a default constructor of your own.
So, you need to either:
give Card a default constructor, eg:
class Card {
private:
Suit s;
Rank r;
public:
Card() : s(), r() {} // <-- HERE
Card(Suit suit, Rank rank) : s(suit), r(rank) {}
...
};
Or:
class Card {
private:
Suit s;
Rank r;
public:
Card() : Card(Suit(), Rank()) {} // <-- HERE
Card(Suit suit, Rank rank) : s(suit), r(rank) {}
...
};
Or:
class Card {
private:
Suit s{};
Rank r{};
public:
Card() = default; // <-- HERE
Card(Suit suit, Rank rank) : s(suit), r(rank) {}
...
};
use the std::vector's push_back() or emplace_back() method instead of the resize() method when populating the cardVector with new Cards, eg:
CardDeck::CardDeck(){
//cardVector.resize(52);
cardVector.reserve(52);
//int index = 0;
for (int suit = 0; suit < 4; suit++){
for (int rank = 0; rank < 13; rank++){
//cardVector.at(index) = Card(static_cast<Suit>(suit), static_cast<Rank>(rank));
cardVector.push_back(Card(static_cast<Suit>(suit), static_cast<Rank>(rank)));
//or:
cardVector.emplace_back(static_cast<Suit>(suit), static_cast<Rank>(rank));
//index++;
}
}
}
That being said, since a deck has a fixed 52 Cards, you might consider using a fixed-sized array (or std::array) instead of std::vector.

Initializing an object as in a vector class [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 11 months ago.
Improve this question
So, I know a vector object can be declared and initialized like this:
// Nothing new here. I know <int> is a template
// and how to implement it:
vector <int> vect{ 10, 20, 30 };
I assume that the vector object has inside an array of values, and the functions of that class (like push_back() for example) manage it. I would like and have been trying to implement something like that in a class of my own, without success. Would be interesting being able to understand how it's done! Did many "experiments" but none worked.
// Random named class:
class A_Class
{
private:
// A pointer for the type I want:
int *A_pointer_To_int;
public:
// Trying to accept the input values between
// brackets and putting them inside a temp array:
A_Class(int Input_Array[]) {}
};
int main()
{
// trying to create the object like in the vector class.
// Returns error "No instance of constructor matches the argument list":
A_Class My_Object{1,2,3}
return 0;
}
In a function parameter, int Input_Array[] is just syntax sugar for a decayed pointer int* Input_Array, which does not provide any information about any array that may be passed in to it.
For what you are attempting, you need to accept a std::initializer_list instead, eg:
#include <initializer_list>
#include <algorithm>
// Random named class:
class A_Class
{
private:
// A pointer for the type I want:
int *A_pointer_To_int;
// the number of values in the array:
size_t size;
public:
A_Class(std::initializer_list<int> Input_Values) {
size = Input_Values.size();
A_pointer_To_int = new int[size];
std::copy(Input_Values.begin(), Input_Values.end(), A_pointer_To_int);
}
~A_Class() {
delete[] A_pointer_To_int;
}
};
int main()
{
A_Class My_Object{1,2,3}; // works now
return 0;
}
Online Demo

c++ classes with parameters and comparisons [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 9 years ago.
Improve this question
let's say i have a class of type human and i want to create a method function called jim.punch(billy); i created jim and i created billy. how do i refer to jim when i'm writing the function? let's say whatever returns is based on their weight. so if billy is bigger, something will happen and something else will happen if jim is bigger. i just don't know how to use jim in the function
#include <iostream>
using namespace std;
class dog
{
public:
int age;
int weight;
int height;
int punch(int);
};
int jim::punch(x)
{
if (jim > x) <------------------
{
return //something
}
else
{
return something
}
int main()
{
human jim;
jim.age = 30";
jim.weight = 175;
jim.height = 6;
human billy; //etc
jim.punch(billy);
return 0;
}
You should really follow a good book (or at least a good online tutorial); your question shows confusion about very basic C++ concepts.
Nevertheless, here's an answer to your particular situation (omitting loads of details and important-but-not-for-this-particular-case concepts). human is a class. Classes can have data members and member functions. Many instances (or obejcts) of a class type can exist; each of these has its own values of data members.
Each member function can access the members (data and functions) of the instance on which it was invoked. It can do so explicitly (using the keyword this which represents a pointer to the instance), or implicitly (just naming the data member).
So here's how you might express your situation in code:
class human
{
//place data members such as age, height, weight here
public:
int punch(const human &target);
};
int human::punch(const human &target)
{
std::cout << "PUNCH!";
if (weight > target.weight) //equivalent to this->weight > target.weight
{
return /* something which represents this object winning */
}
else
{
return /* something which represents target object winning */
}
//Note: you should handle == case as well
}
int main()
{
human jim, billy;
jim.punch(billy);
}

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;
};

Pointer Issues "cannot instantiate abstract class" [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 9 years ago.
Improve this question
Doing a programming homework assignment and I am having some trouble with pointers. I'm not too sure what the issue is.
I have looked around and found a few solved issues but I can't seem to figure out how to implement the fixes in my own code. (noob)
in my main I call:
MotherShip* m1 = new MotherShip(5, 6);
I am getting the error "cannot instantiate abstract class" with this.
MotherShip.h:
#include "SpaceShip.h"
class MotherShip : public SpaceShip
{
public:
int capacity;
MotherShip();
MotherShip(int x, int y, int cap);
MotherShip(const MotherShip& ms);
void print();
};
MotherShip.cpp:
#include "stdafx.h"
#include "MotherShip.h"
MotherShip::MotherShip()
{
}
MotherShip::MotherShip(int x, int y, int cap)
{
}
MotherShip::MotherShip(const MotherShip& ms)
{
}
void MotherShip::print()
{
}
Here is my full main (I don't think it's important here so I thought I'd just pastie it)
http://pastie.org/pastes/8429256/text
You're passing two arguments to your class constructor, however you have not defined a constructor that takes two arguments.
One solution would be:
MotherShip* m1 = new MotherShip(5, 6, 7 /* passing third argument */);
Another solution is defining a constructor to take two arguments:
MotherShip(int x, int y);
you must set the cap parameter as your constructor requires it.
There's no constructor that takes two ints!
Use the default value in your declaration
MotherShip(int x, int y, int cap = 123);
or, as an alternative, declare and define another constructor that takes two ints:
MotherShip(int x, int y);
Could be guessed without looking. abstract class in C++ is implemented by adding a pure virtual function.
You sure have a pure virtual function in your base class SpaceShip which you need to override in MotherShip. Or else MotherShip too becomes abstract and cannot be instantiated.
class SpaceShip
{
public:
virtual void DoSomething() = 0; //override this with some implementation in MotherShip
};