about objects and functions

i'm trying do 1 thing, but i'm 'stuck' :(
i try the functions pointers too, but without sucess :(

i understand the objects are the way for work with class's. until here fine.
but why i can't change the virtual functions from an object? is there anyway for do it?
i can't do, outside of class\functions, these code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

using namespace std;

class test
{
public:
   virtual void created(){};
   test()
   {
         created();
   }
};

test a;

void a::created()
{
   cout << "hello world";
}

int main()
{
   cin.get();
}

how i can validate these line:
void a::created()
???
Virtual functions cannot be changed within an object. They have to be overridden in a derived class. I think what you want to do is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>

using namespace std;

class test
{
public:
   virtual void created(){};
   void run() { created(); }
};

class test2 : public test
{
public:
   virtual void created();
};

void test2::created()
{
   cout << "hello world";
}

int main()
{
   test2 a;
   a.run();
   cin.get();
}


Notice, I took the virtual function call out of the constructor. It is undefined behavior (I believe) to call a virtual function from within a constructor. I'm sure one of the other forum denizens will quote the appropriate paragraph from the standard (or prove me wrong).

The tutorial on this site is excellent. It is worth the effort to go through. To learn more about virtual functions and polymorphism, see the following chapter:
http://www.cplusplus.com/doc/tutorial/polymorphism/
Last edited on
sorry what i need is object polymorphism
Topic archived. No new replies allowed.