Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Draw Vector of pointers to a class = crash  (Read 1653 times)

0 Members and 1 Guest are viewing this topic.

pinko64

  • Newbie
  • *
  • Posts: 12
    • View Profile
Draw Vector of pointers to a class = crash
« on: October 03, 2011, 02:56:45 am »
So i made a function, which makes new tysy object when it's called.
It then pushes the objects to a vector:

Code: [Select]

void piirto::CreateCan()
{
tysy *Can1 = new tysy(Win);
      std::cout << "Object " << Can1 << " says..." << std::endl;
Can1->Hello();
   std::cout << std::endl <<  std::endl;
 Can1++;
    Tyz.push_back(Can1);
}


Now in my mainloop i have:

Code: [Select]

//blabla
    Win.Clear();
    goDraw();
    Win.Draw(p12.s_tysy); //This draws fine.

    Win.Display();


Now the goDraw(); function has :

Code: [Select]

if (i want to do this .. .. . .)
                    for (int i = 0; i < Tyz.size(); ++i)
                            {
                                 Tyz[i]->Hello("buu");
                                 Win.Draw(Tyz[i]->s_tysy); // Crash

                            }


If i call Tyz->Hello("buu"); It prints buu nice and soundy.
But whenever i try to draw those same sprites from s_tysy members using pointers to objects it causes a crash.
Program compiles good.

So if i just make normal tysy object i can draw it's sprite ok.
So why is this pointer thing crashing it?

Code: [Select]
tysy
   .h
        sf::Image       i_tysy;
        sf::Sprite      s_tysy;


   .cpp
i_tysy.LoadFromFile("kanuuna.jpg");
   s_tysy.SetImage(i_tysy);
   s_tysy.SetScale(0.4,0.4);
   s_tysy.SetColor(sf::Color(255,0,0,255));


Any help & instructions are welcome!

Nexus

  • SFML Team
  • Hero Member
  • *****
  • Posts: 6286
  • Thor Developer
    • View Profile
    • Bromeon
Draw Vector of pointers to a class = crash
« Reply #1 on: October 03, 2011, 03:04:06 am »
Code: [Select]
tysy *Can1 = new tysy(Win);
std::cout << "Object " << Can1 << " says..." << std::endl;
Can1->Hello();
std::cout << std::endl <<  std::endl;
Can1++;
Tyz.push_back(Can1);
You may not increment the pointer, this is undefined behavior.

I think you don't even need pointers. Why not objects? They are easier to handle, you don't have to delete anything:
Code: [Select]
std::vector<tysy> Tys;
...
tysy Can1(Win);
Can1.Hello();
Tyz.push_back(Can1);

By the way, what is a tysy? :D
Zloxx II: action platformer
Thor Library: particle systems, animations, dot products, ...
SFML Game Development:

 

anything