No Default constructor to run functions in c++? - c++

i want to run the function Run in the main, but am not allowed to create object due to no default constructor. when i try to create the default constructor, i receive the message, 'Error"Game::Game int maxComponents)" provides no initialiser for:'
//Game.h
#pragma once
#include "GameComponent.h"
#include <time.h>
class Game
{
private:
int componentCount;
GameComponent** components;
const int TICKS_1000MS;
public:
Game(){} //this does not work either
Game(int maxComponents){} //this does not work as my default constructor
~Game();
void Add(GameComponent*);
void Run();
};
//Game.cpp
#pragma once
#include "StdAfx.h"
#include "Game.h"
#include <iostream>
#include<time.h>
using namespace std;
void Game::Add(GameComponent*)
{
components= new GameComponent*[componentCount];
}
void Game::Run()
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
//cout << timeinfo->tm_hour<< ":" << timeinfo->tm_min << ":" << timeinfo->tm_sec << endl;
for(int n=0;n<componentCount;n++)
{
components[n]->Update(timeinfo);
}
}
Game::~Game()
{
}
//main.cpp
#include "stdafx.h"
#include <iostream>
#include "Game.h"
#include <time.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
Game obj1;
obj1.Run();
system("pause");
return 0;
}
So, how do i create a default constructor here? i've tried to use member initialising too, doesn't work. and copy constructor.

A default constructor is a constructor that takes no arguments. So, you should declare a constructor that looks something like this:
Game() { }
You can keep your other constructor - normal function overloading applies to constructors, so it will use your Game(int) constructor when you specify a single integer argument, and Game() when you specify no arguments.
However, in your case Game contains a const int member (TICKS_1000MS). Since it's const, it's expected to be initialized in the constructor. So you should do something like this:
Game() : TICKS_1000MS(123) { } // replace 123 with whatever the value should be
You need to do that for all constructors.
It's a little silly to have a non-static const member of a class which is always initialized to the same value (as opposed to a value passed in as an argument to the constructor). Consider making it an enum instead:
enum { TICKS_1000MS = 123 };
or, a static const member:
static const int TICKS_1000MS;
and initialize it in Game.cpp:
const int Game::TICKS_1000MS = 123;

As long as you have defined a constructor other than than the default one, the default constructor is not provided anymore so you have to define it manually:
public:
Game() {}
Game(int maxComponents){}
Now you have a default constructor and an overloaded constructor which takes 1 integer parameter.

You will need to create the default parameterless constructor. When you define a constructor you no longer get the default that would have been created behind the scenes.
Game(){}

The default constructor is the one that does not take any parameters, in your case Game(){}.
You do not seem to use the constructor parameter, but if you do, you will have to provide a default value.

Probably you can so something along these lines, you class Game needs to initialize const int in both the constructors:
class Game
{
private:
int componentCount;
GameComponent** components;
const int TICKS_1000MS;
public:
Game(): TICKS_1000MS(100)
{} //this does not work either
Game(int maxComponents): TICKS_1000MS(100)
{} //this does not work as my default constructor
~Game();
void Add(GameComponent*);
void Run();
};
As pointed out by others you need to intialize const data in ctor or initializer list.

Related

Default constructor that calls peer constructor with unique_ptr move

I am trying to make a class with two constructors. One that is a default constructor, the other calling the parameterized constructor. I get a compiler error that tells me that I cannot use move on the object just created and I sort of understand that it doesn't like to do that, because there is no real assignment here.
How can I achieve the right behavior? I am trying to avoid writing two constructors that initialize the variables. An initialization function might work, but then I would have to fill the body of the constructors and I was trying to come up with a neat solution like shown below.
#include <string>
#include <iostream>
#include <memory>
using namespace std;
class Foo
{
public:
Foo(unique_ptr<int>& number) : m_number(move(number))
{
}
Foo() : Foo(make_unique<int>(54))
{
}
void print()
{
cout << m_number << endl;
}
private:
unique_ptr<int> m_number;
};
int main()
{
Foo f;
f.print();
return 0;
}
main.cpp:18:33: error: invalid initialization of non-const reference
of type ‘std::unique_ptr&’ from an rvalue of type
‘std::_MakeUniq::__single_object {aka std::unique_ptr}’
Foo() : Foo(make_unique(54))
I decided to go for an rvalue constructor. This seems to resolve the issue for me.
#include <string>
#include <iostream>
#include <memory>
using namespace std;
class Foo
{
public:
// rvalue constructor so that we can move the unique_ptr.
Foo(unique_ptr<int>&& number) : m_number(move(number))
{
}
Foo() : Foo(make_unique<int>(54))
{
}
void print()
{
cout << *m_number << endl;
}
private:
unique_ptr<int> m_number;
};
int main()
{
Foo f;
f.print();
unique_ptr<int> a = make_unique<int>(33);
Foo f2(move(a)); // important to do a move here, because we need an rvalue.
f2.print();
return 0;
}

Why Do I get this error on vector initialisation?

I have a problem with vector declaration and initialization in a
class constructor. I have a Station.h and Station.cpp files of a class and I recall it in main :
Station.h
#ifndef STATION_H
#define STATION_H
#include <vector>
class Station
{
public:
int num_bin;
int num_staz;
vector<int> binari; //here already gives me error! Vector does not name a type
Station(int num_staz, int num_bin);
virtual ~Station();
Station(const Station& other);
protected:
private:
};
Then I want to initialize the vector in the constructor of .cpp like that:
Station.cpp
#include "Station.h"
using namespace std;
Station::Station(int num_staz, int num_bin)
{
this->num_bin = num_bin;
this->num_staz = num_staz;
this->binari(num_bin); //here I want to create a vector of num_bin size
}
and then call it in main like that:
main.cpp
#include <iostream>
#include "Station.h"
using namespace std;
int main()
{
Station staz1(2,3);
staz1.binari.push_back(300); // error! class Station has no member binari
staz1.binari.push_back(250);
staz1.binari.push_back(150);
return 0;
}
Where am I making a mistake?
this->binari(num_bin); //here I want to create a vector of num_bin size
The function you need to use is std::vector::resize().
this->binari.resize(num_bin);
It will be better to initialize the object with the appropriate size as:
Station::Station(int num_staz, int num_bin) : num_bin(num_bin),
num_staz(num_staz),
binari(num_bin)
{
}
this->binari(num_bin); This doesn't work because it is not an initialization that is why it doesn't work.
To make this work use it in in-class initialization list:
Station::Station(int num_staz, int num_bin) :
num_bin(num_bin),
num_staz(num_staz),
binari(num_bin)
{
}

How to make object of Parcel2 class in main function

I've separate implementation and defination of methods. Now i doesn't understand how to make object/instance of Parcel2 class in Main.cpp file. I also write in Main.cpp Parcel2::Parcel2(2); but it log saying constructor cannot call directly. kindly guide me.
Parcel2.h
#ifndef PARCEL2_H
#define PARCEL2_H
class Parcel2
{
private:
// Declare data members
int id;
public:
// Constructor
Parcel2(int id);
// Setter function
void setID(int id);
// getter function
int getID();
protected:
};
#endif
Parcel2.cpp
#include "Parcel2.h"
// Defination of constructor
Parcel2::Parcel2(int id) {
this->id = id;
}
// Defination of setter
void Parcel2::setID(int id) {
this->id = id;
}
// Defination of getter
int Parcel2::getID() {
return id;
}
Main7.cpp
#include <iostream>
#include "Parcel2.h"
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
// how to make object
}
If you are trying to create a Parsel2 object on the stack (as a local variable), you can just declare a variable with an integer argument. (The integer argument is needed because your constructor requires an argument.) For example:
Parcel2 obj(2);
Here is an alternative C++ 11 syntax, which some (me) find easier to parse:
auto obj = Parcel2(2);
If instead you want to dynamically allocate a Parsel2, you need to allocate it with new:
Parcel2 * obj = new Parcel2(2);
And once again, an alternative syntax:
auto obj = new Parcel2(2);
As a final note, please consider assigning class members using a member initialization list:
Parcel2::Parcel2(int id) : id(id)
{}

How to create an object with the constructor with parameter

For some reason whenever I try running my code it always call the default constructor but it should be calling the constructor with parameters.
#include "pokemon.h"
int main()
{
int choice;
cout<<"input 1 2 or 3"<<endl;
cin>>choice;
if(choice==1||choice==2||choice==3)
{
pokemon(choice);
}
}
in my headerfile i have
#include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h>
using namespace std;
class pokemon{
public:
pokemon();//default constructor
pokemon(int a);
~pokemon();//desconstructor
pokemon(const pokemon& c);
void train();
void feed();
bool isnothappy();
string getName();//accessor for the name
int getPowerlevel();//accessor for the power level
string getColor();//accessor for the color
string getType();//accessor
int getHappylevel();//accessor
static int getNumObjects();
void set_type(string);//mutator
void set_color(string);//mutator
void set_power_level(int);//mutator
void set_happy_level(int);//mutator
void set_name(string);//mutator
private:
string name;
string color;
string type;
int power_level;
int happy_level;
static int numberobject;
};
and in my other .cpp file i have
int pokemon::numberobject=0;//initialize static member variable
pokemon::pokemon(){//default constructor
name="pikachu";
color="yellow";
type="electric";
power_level=0;
happy_level=1;
cout<<"The default constructor is being called"<<endl;
++numberobject;
}
pokemon::pokemon(int a)
{
if(a==0)
{
name="Pikachu";
color="yellow";
type="electric";
power_level=1;
happy_level=1;
}
else if(a==1)
{
name="Bulbasaur";
color="green";
type="grass";
power_level=1;
happy_level=1;
}
else if(a==2)
{
name="Charmander";
color="red";
type="fire";
power_level=1;
happy_level=1;
}
else if(a==3)
{
name="Squritle";
color="blue";
type="water";
power_level=1;
happy_level=1;
}
cout<<"Congratulations you have chosen "<<getName()<<". This " <<getColor()<<" "<<getType()<<" pokemon is really quite energetic!"<<endl;
++numberobject;
}
pokemon::~pokemon()
{
//cout<<"the destructor is now being called"<<endl;
//cout<<"the number of objects before the destructor is "<<pokemon::getNumObjects()<<endl;
--numberobject;
cout<<"Now you have a total number of "<<pokemon::getNumObjects()<<endl;
}
pokemon::pokemon(const pokemon& c)//copy constructor
{
name=c.name;
color=c.color;
type=c.type;
power_level=c.power_level;
happy_level=c.happy_level;
++numberobject;
}
I have both my constructors declared and defined in my other files but this darn thing always calls the default constructor
This code:
pokemon(choice);
means the same as:
pokemon choice;
It declares a variable called choice of type pokemon, and there are no arguments given to the constructor. (You're allowed to put extra parentheses in declarations in some places).
If you meant to declare a variable where choice is a constructor argument then you have to write:
pokemon foo(choice);
If you meant to create a temporary object (which will be immediately destroyed) with choice as argument, you can write (pokemon)choice;, or pokemon(+choice);, or since C++11, pokemon{choice};.
This issue with ambiguity between declarations and non-declarations can arise any time a statement begins with a type-name followed by (. The rule is that if it is syntactically correct for a declaration then it is treated as a declaration. See most-vexing-parse for other such cases.

How can I initialize char arrays in a constructor?

I'm having trouble declaring and initializing a char array. It always displays random characters. I created a smaller bit of code to show what I'm trying in my larger program:
class test
{
private:
char name[40];
int x;
public:
test();
void display()
{
std::cout<<name<<std::endl;
std::cin>>x;
}
};
test::test()
{
char name [] = "Standard";
}
int main()
{ test *test1 = new test;
test1->display();
}
And sorry if my formatting is bad, I can barely figure out this website let alone how to fix my code :(
If there are no particular reasons to not use std::string, do use std::string.
But if you really need to initialize that character array member, then:
#include <assert.h>
#include <iostream>
#include <string.h>
using namespace std;
class test
{
private:
char name[40];
int x;
public:
test();
void display() const
{
std::cout<<name<<std::endl;
}
};
test::test()
{
static char const nameData[] = "Standard";
assert( strlen( nameData ) < sizeof( name ) );
strcpy( name, nameData );
}
int main()
{
test().display();
}
Your constructor is not setting the member variable name, it's declaring a local variable. Once the local variable goes out of scope at the end of the constructor, it disappears. Meanwhile the member variable still isn't initialized and is filled with random garbage.
If you're going to use old-fashioned character arrays you'll also need to use an old-fashioned function like strcpy to copy into the member variable. If all you want to do is set it to an empty string you can initialize it with name[0] = 0.
Since you are using C++, I suggest using strings instead of char arrays. Otherwise you'd need to employ strcpy (or friends).
Also, you forgot to delete the test1 instance.
#include <iostream>
#include <string>
class test
{
private:
std::string name;
int x;
public:
test();
void display()
{
std::cout<<name<<std::endl;
}
};
test::test()
{
name = "Standard";
}
int main()
{
test test1;
test1.display();
std::cin>>x;
}
Considering you tagged the question as C++, you should use std::string:
#include <string>
class test
{
private:
std::string name;
int x;
public:
test();
void display()
{
std::cout<<name<<std::endl;
std::cin>>x;
}
};
test::test() : name("Standard")
{
}
c++11 actually provides two ways of doing this. You can default the member on it's declaration line or you can use the constructor initialization list.
Example of declaration line initialization:
class test1 {
char name[40] = "Standard";
public:
void display() { cout << name << endl; }
};
Example of constructor initialization:
class test2 {
char name[40];
public:
test2() : name("Standard") {};
void display() { cout << name << endl; }
};
You can see a live example of both of these here: http://ideone.com/zC8We9
My personal preference is to use the declaration line initialization because:
Where no other variables must be constructed this allows the generated default constructor to be used
Where multiple constructors are required this allows the variable to be initialized in only one place rather than in all the constructor initialization lists
Having said all this, using a char[] may be considered damaging as the generated default assignment operator, and copy/move constructors won't work. This can be solved by:
Making the member const
Using a char* (this won't work if the member will hold anything but a literal string)
In the general case std::string should be preferred