d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Default Values For Constructor Parameters > I Do Not Understand Why It Doesn't Work.
Add Reply New Topic New Poll
Member
Posts: 788
Joined: Feb 19 2010
Gold: 30.60
May 31 2012 01:15pm
Header file :

Code

#ifndef SPRITE_H
#define SPRITE_H
#include "Image.h"

class Sprite
{
private:
Image image;
int x;
int y;
public:
Sprite(const Image img, const int x = 0, const int y = 0);
...

int getX(){return x;}
int getY(){return y;}
};
#endif


Class file :

Code

#include "Sprite.h"
#include "Image.h"


Sprite::Sprite(Image img, int x, int y) : image(img), x(x), y(y)
{
}





this is what I do

Code

Sprite* sprite = new Sprite(new Image());
int pointerX = sprite -> getX();

Sprite other = Sprite(new Image());
int valueX = sprite.getX();


Now pointerX is 0 as I expected.
But valueX is some large negative integer.
I really do not understand why this is.
I'm quite new to C++ and I would appreciate any help.
Member
Posts: 4,605
Joined: Sep 15 2011
Gold: 9,464.00
May 31 2012 01:29pm
http://stackoverflow.com/questions/5279042/placement-new-vs-explicit-constructor-call-in-c

Read the first answers and the comments under it.

Short answer is: the first calls the constructor, the second calls the copy constructor.

This post was edited by irimi on May 31 2012 01:30pm
Member
Posts: 788
Joined: Feb 19 2010
Gold: 30.60
May 31 2012 01:32pm
Thanks alot!
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll