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
Related
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 7 years ago.
Improve this question
In a member function of Class Championship, I try to create dynamic objects and call the member function of Class Game, but I got the error message as error: expected primary-expression before '[' token. How to correct it?
class Championship
{
public:
Championship(string,int);
void CreateGame();
void display();
private:
int gamenum;
};
class Game
{
public:
friend class Championship;
void Getteam();
};
void Championship::CreateGame()
{
Game *game = new Game[gamenum];
for (int i = 0; i < gamenum; i++)
Game[i].Getteam();
}
The exact problem you are facing in your code is in this small bit
Game *game = new Game[gamenum];
for (int i = 0; i < gamenum; i++)
Game[i].Getteam();
The main issue here is that you have declare an array of type Game and call it game but then you try to access using Game which is the type, so simply swapping that back to game would fix that issue.
However, there is no need for using raw pointers in this way. std::vector is superior in so many ways here. It allows you to dynamically add more and more objects into the container in a safe way. I was about to show how std::vector could be used in your Championship::CreateGame() function... but I can't really work out what it is trying to do...
I also don't see why you have the friend line in your game class... that is used to give another class 'full' access to your class, ie the Championship class is given access to private members of Game.
Edit: While this answer doesn't directly solve the problem, it does provide a useful alternative syntax for allocating arrays of User-Defined Objects.
This can probably be solved not-so-elegantly using the classic C-style double-pointer array (i.e. argv from int main(int argc, char** argv). Such code would first allocate the space for the array, and then allocate the space for each individual object using a loop with an index.
#include <iostream>
class Foo
{
public:
//Constructor to ensure each object is unique with an int + loop
Foo(int k)
: i(k)
{}
int i;
int operator() () {return i;}
};
int main ()
{
//Arbitrary number for allocation; get this somehow
int i = 5;
//Although it can be unsafe, allocate an array of pointers with a pointer to pointer
Foo** array = new Foo*[i];
for (int j = 0; j < i; ++j)
{
array[j] = new Foo(j);
//Here, I use operator() to test that each object is unique.
std::cout << (*array[j])() << std::endl;
}
//Using Coliru, the program will work and print out this
std::cout << "this worked!\n";
return 0;
}
Coliru: http://coliru.stacked-crooked.com/a/84f7641e5c4fa2f3
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 8 years ago.
Improve this question
I am using a c library to do integration, where the integrand is declared as fun(...,void *fdata,...)
which uses *fdata pointer to pass external variables, however, before doing numerical integration, I need to
interpolate the raw data using other c++ libraries, giving back some interpolating class objects,
basically I want to pass these objects to a integrand which is user-defined ...
You could use an structure and pass a pointer to it but it seems to me that you don't have a fixed number of objects to pass and therefore that an object aggregating others dynamically would suit better your needs so you can use a std::vector and pass its address as func fdata parameter.
An example:
#include <vector>
#include <iostream>
using namespace std;
class C //Mock class for your objs
{
public:
C(int x)
{
this->x = x;
}
void show()
{
cout << x << endl;
}
private:
int x;
};
void func(void *fdata) //Your function which will recieve a pointer to your collection (vector)
{
vector <C *> * v = (vector<C *> *)fdata; //Pointer cast
C * po1 = v->at(0);
C * po2 = v->at(1);
po1->show();
po2->show();
}
int main()
{
vector<C *> topass;
topass.push_back(new C(1)); //Create objects and add them to your collection (std::vector)
topass.push_back(new C(2));
func((void *)(&topass)); //Call to func
for(vector<C *>::iterator it = topass.begin(); it != topass.end(); it++)
delete(*it);
}
This question already has answers here:
How to make an array with a dynamic size? General usage of dynamic arrays (maybe pointers too)? [closed]
(5 answers)
Closed 8 years ago.
In a project that I'm working on, I need to make a class that contains an array of pointers to other objects of the same class. I'm currently having trouble initializing this array.
Example:
class MrClass{
MrClass* otherInstances[];
public:
MrClass(MrClass* x[]){
otherInstances = x;
}
}
This array must be arbitrarily sized, since the number of instanced of the class to be passed is defined at compile time and it must be of pointers because multiple instances of the class must have access to the same objects.
Correct solution
Use std::vector<MrClass *> or std::array<MrClass *>. Or even better, std::vector<std::shared_ptr<MrClass>>
class MrClass{
std::vector<std::shared_ptr<MrClass>> otherInstances;
public:
MrClass(std::vector<std::shared_ptr<MrClass>> const & x)
: otherInstances(x)
{
}
}
Auxiliary solution
If you really need an array (and you really know, what you're doing), do the following:
class MrClass{
MrClass ** otherInstances;
int otherInstancesCount;
public:
MrClass(MrClass ** x, int count){
otherInstances = x;
otherInstancesCount = count;
}
}
Arbitrarily sized arrays are written std::vector in C++. So
you'd have:
class MrClass
{
std::vector<MrClass*> otherInstances;
public:
MrClass( std::vector<MrClass*> const& initialValues )
: otherInstances( initialValues )
{
}
};
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I have tried to make some sort of card game here but the classes for the holder / cardpile don't give away right things to the reciver/player and I don't know how to sort this out.
Here is the program:
#include <iostream>
using namespace std;
class subclass // like a card
{
public:
subclass();
subclass(int x);
int nummer;
int getnummer();
};
subclass::subclass():nummer(0){}
subclass::subclass(int x):nummer(x){}
int subclass::getnummer()
{
return nummer;
}
holder class:
class holder // like a cardpile
{
public:
holder();
subclass cardpile[2];
subclass* pile; // a cardpile which has 2 cards, with nummber 1 and 2.
subclass* getsubclass(int i); // take first or second card.
};
holder::holder()
{
subclass first(1*3);
subclass second(2*3);
pile=cardpile;
pile=&first;
pile++;
pile=&second;
pile--;
}
subclass* holder::getsubclass(int i) //1 eller 2.
{
return pile+i;
}
reciver class/ the player
class reciver // like a player
{
public:
subclass part_of_holder;
reciver();
void getsubclass( subclass* in); // give this card to player from this pointer
void showinside(); // what card do player have
};
reciver::reciver():part_of_holder(){}
void reciver::getsubclass( subclass* in)
{
part_of_holder=*in;
}
void reciver::showinside() // what card do player have
{
cout<< part_of_holder.getnummer();
}
and the main
int main()
{
holder cardpile;
reciver player;
cout << "first card should be 1*3 and it is : " ;
player.getsubclass(cardpile.getsubclass(0));
player.showinside();
cout << endl <<"first card should be 2*3 and it is : " ;
player.getsubclass(cardpile.getsubclass(1));
player.showinside();
return 0;
}
In the end all I get is nonsence
holder::holder()
{
subclass first(1*3);
subclass second(2*3);
pile=cardpile;
pile=&first; // WRONG
pile++;
pile=&second; // WRONG
pile--;
}
The two lines above dont do what I suspect you think they do.
If you are trying to assign in the cardpile you would need something more like this:
cardpile[0] = first or *pile = first.
Sadly they wont work, since you dont have copy constructors. You also dont have any way to set a subclass's nummer field once constructed, so you are slightly doomed.
Add a setter function to the get instruction, and you could write this:
cardpile[0].setnummer(first.getnummer());
This is not going to work
holder::holder()
{
subclass first(1*3); // create temporary
subclass second(2*3); // create another temoporary
pile=cardpile; // assign member pointer to another member!!!
pile=&first; // assign member pointer to temporary
pile++;
pile=&second; // assign member pointer to temporary
pile--;
}
// member pointer pile points to object that no longer exists!!!
Basically once you create an instance of holder its internal pile pointer points to an object that no longer exists and that alone makes your class unstable because your getsubclass method returns an offset of this pointer - thus any attempt to dereference it will likely segfault.
In all honesty you would be better to start off again from scratch but a way of ensuring that you assign these temporaries to your member array would be
cardpile[0] = subclass(1*3);
cardpile[1] = subclass(2*3);
pile = cardpile;
however, the way this code is written is not a good design and I would advise starting from scratch when your grasp of C++ is better.
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
};