473,320 Members | 1,841 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Defining a class on the fly

I want to create a few objects which all share a lot of common features,
so they should all derive from the same base class. However, each of
them needs individual definitions of two functions. So what I'd like to
do is to create a new object which is based on a class with virtual
functions, and define the virtual function when the object is created,
without having to define a new class for each object. Is there a good
way to do this in C++? (I know it's possible in Java.)

I suppose another way to go is to use funtion pointers, but I's like to
stay OO as much as I can.

Thanks,
Martin
Jul 19 '05 #1
8 2674


Martin Magnusson wrote:

I want to create a few objects which all share a lot of common features,
so they should all derive from the same base class. However, each of
them needs individual definitions of two functions. So what I'd like to
do is to create a new object which is based on a class with virtual
functions, and define the virtual function when the object is created,
without having to define a new class for each object. Is there a good
way to do this in C++? (I know it's possible in Java.)

I suppose another way to go is to use funtion pointers, but I's like to
stay OO as much as I can.


Could you reformulate?

At the moment it sounds as if you want to create a class and more important
the implementation of some functions during runtime.
This is not possible in C++. At least not in a standard conforming way.
The non standard solution would be: create a sort of plugin mechanism,
write your C++ class definition to a file, start the C++ compiler from
your application (if it can be found) and connect the new object module
through the plugin mechanism. But none of the above is standard C++
and to be honest: I never had the need for doing this.

Just curious: What are this functions you want to create at runtime.
If we know more about it, maybe someone might show you a C++ way to
do it.

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 19 '05 #2
"Martin Magnusson" <ma******@student.uu.se> wrote in message
news:3F***************@student.uu.se...
I want to create a few objects which all share a lot of common features,
so they should all derive from the same base class. However, each of
them needs individual definitions of two functions. So what I'd like to
do is to create a new object which is based on a class with virtual
functions, and define the virtual function when the object is created,
without having to define a new class for each object. Is there a good
way to do this in C++? (I know it's possible in Java.)

I suppose another way to go is to use funtion pointers, but I's like to
stay OO as much as I can.

What do you mean exactly by 'defining' the function? How can you create
code on the fly, unless you have a full C++ compiler embedded into your
apps? If you have a set of function which you would like to assign
dynamically, then use function pointers. Whether this is good design or not,
I do not know .. what do you want to do this for?

hth
--
jb

(replace y with x if you want to reply by e-mail)
Jul 19 '05 #3
Karl Heinz Buchegger wrote:
Could you reformulate?


Sure! Say I have a class that looks something like this:

class MaxNode
{
public:
virtual float ValueOf( Sensation* s ) = 0;
virtual bool IsTerminated( Sensation* s ) = 0;
void AddChild( MaxNode* m );
std::string ToString();
private:
Sensation* previousSensation;
Reward* previousReward;
}

Now, for each actual Max node I need to define what ValueOf() and
IsTerminated() should do, and this will be different for all, or most,
of the MaxNode objects I create.

Naturally, I could write a new class for each object and then create a
new object of that class, but since I would only create one object of
each class, I would like to do something like this, which should create
a pointer to an object called Root, which is of an unnamed class derived
from MaxNode:

MaxNode* Root = new MaxNode
{
float ValueOf( Sensation* s )
{
...
}
bool IsTerminated( Sensation* s )
{
...
}
// and possibly add some extra private fields:
private:
int extraData;
};
Does this make it any clearer?

/ Martin
Jul 19 '05 #4
"Martin Magnusson" <ma******@student.uu.se> wrote in message
news:3F***************@student.uu.se...
Karl Heinz Buchegger wrote:
Could you reformulate?


Sure! Say I have a class that looks something like this:

class MaxNode
{
public:
virtual float ValueOf( Sensation* s ) = 0;
virtual bool IsTerminated( Sensation* s ) = 0;
void AddChild( MaxNode* m );
std::string ToString();
private:
Sensation* previousSensation;
Reward* previousReward;
}

Now, for each actual Max node I need to define what ValueOf() and
IsTerminated() should do, and this will be different for all, or most,
of the MaxNode objects I create.

Naturally, I could write a new class for each object and then create a
new object of that class, but since I would only create one object of
each class, I would like to do something like this, which should create
a pointer to an object called Root, which is of an unnamed class derived
from MaxNode:

MaxNode* Root = new MaxNode
{
float ValueOf( Sensation* s )
{
...
}
bool IsTerminated( Sensation* s )
{
...
}
// and possibly add some extra private fields:
private:
int extraData;
};
Does this make it any clearer?

Yes :o)

I assume only those functions will change and the rest will remain
untouched? In this case, you have a some options.

a) You create have a function pointer to a 'regular' function in the
class and assign it a pointer to the wanted function on runtime. It is only
ugly when calling, since it will look a bit like C with emulated classes:
my_class.do_func (myclass, params);

b) The same as a), but with member functions. Though, the calling syntax
looks really ugly: (my_class.*my_class.do_func) (params);

c) Probably the cleanest approach: You make your class a template, that
takes an id (either an int or a value of an enum). Then you create the
/non/-virtual functions ValueOf etc. Inside those functions you put a huge
switch statement that executes code based on the template parameter of the
class. If you have a good optmizing compiler it will just insert the code
thats needed and remove the switch altogether (since the template parameter
is a compile time constant and you would be switching on that). The
advantage I see, you have all the code of the different 'MaxNode types' in
one place. the disadvantage, your functions in question might become
awefully large.

hth
--
jb

(replace y with x if you want to reply by e-mail)
Jul 19 '05 #5


Martin Magnusson wrote:

Karl Heinz Buchegger wrote:
Could you reformulate?


Just to clearify
Sure! Say I have a class that looks something like this:

class MaxNode
{
public:
virtual float ValueOf( Sensation* s ) = 0;
virtual bool IsTerminated( Sensation* s ) = 0;
void AddChild( MaxNode* m );
std::string ToString();
private:
Sensation* previousSensation;
Reward* previousReward;
}

Now, for each actual Max node I need to define what ValueOf() and
IsTerminated() should do, and this will be different for all, or most,
of the MaxNode objects I create.
But you know at compile time, what those functions should do? Your original
post sounded as if even that decision should be delayed until runtime.

Naturally, I could write a new class for each object and then create a
new object of that class, but since I would only create one object of
each class, I would like to do something like this, which should create
a pointer to an object called Root, which is of an unnamed class derived
from MaxNode:

MaxNode* Root = new MaxNode
{
float ValueOf( Sensation* s )
{
...
}
bool IsTerminated( Sensation* s )
{
...
}
// and possibly add some extra private fields:
private:
int extraData;
};

Does this make it any clearer?


So your goal is to not have to write all those classes by hand.
Well. Let the compiler do it. Seems like what you want is a templated
class, which takes 2 functions as the template arguments.

Unfortunately I am not good in templates, so I drop out right now.
Anyone else?

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 19 '05 #6
Martin Magnusson wrote:
I want to create a few objects which all share a lot of common features,
so they should all derive from the same base class. However, each of
them needs individual definitions of two functions. So what I'd like to
do is to create a new object which is based on a class with virtual
functions, and define the virtual function when the object is created,
without having to define a new class for each object. Is there a good
way to do this in C++? (I know it's possible in Java.)

I suppose another way to go is to use funtion pointers, but I's like to
stay OO as much as I can.

Thanks,
Martin


I don't know if I understand exactly, but based on what I /think/ you
are doing, I would probably consider something like this:

class FunctionObject
{
public:
int operator()() = 0;
virtual ~FunctionObject() {}
};

class MyClass
{
public:
MyClass(FunctionObject &fo) : func(fo) {}
int DoIt() { return func(); }

private:
FunctionObject &func;
};
Now you supply functions via FunctionObject classes and you can have as
many as you need, plus you can add more later without modifying existing
sources and without re-compiling everything. MyClass can also be made a
base class (don't forget the add a virtual destructor) if that is
necessary for your application (it's not entirely clear to me whether
this was required for other reasons or if you intended to use it as part
of the solution to the problem at hand).

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Jul 19 '05 #7
> Naturally, I could write a new class for each object and then create a
new object of that class, but since I would only create one object of
each class, I would like to do something like this, which should create
a pointer to an object called Root, which is of an unnamed class derived
from MaxNode:


Hi Martin,

As far as I know, there are no unnamed classes in C++ as they are in
java.
However you can define new classes inside of a function/block. That
doesn't safe you a lot coding, but it avoids cluttering your
namespace.

The following example is a little stripped down, but I'm sure you can
expand it to your needs:

#include <memory>

class Base
{
public:
virtual int foo()=0;
virtual ~Base(){};
};
std::auto_ptr<Base> createDerived()
{
class Derived:public Base {
virtual int foo() {
return 42;
}
};
return std::auto_ptr<Base>(new Derived);
}
// Best, Tim
Jul 19 '05 #8

"Karl Heinz Buchegger" <kb******@gascad.at> wrote in message
news:3F***************@gascad.at...


So your goal is to not have to write all those classes by hand.
Well. Let the compiler do it. Seems like what you want is a templated
class, which takes 2 functions as the template arguments.

Unfortunately I am not good in templates, so I drop out right now.
Anyone else?


Like this?

#include <iostream>
#include <string>

class Sensation {};
class Reward {};

class MaxNodeBase
{
public:
virtual ~MaxNodeBase() {};
void AddChild(MaxNodeBase* m );
std::string ToString();
private:
Sensation* previousSensation;
Reward* previousReward;
};

template <bool (*term)(Sensation*), float (*value)(Sensation*) >
class MaxNode : public MaxNodeBase
{
public:
bool IsTerminated( Sensation* s ) { return term(s); }
float ValueOf( Sensation* s ) { return value(s); }
};

bool a_term(Sensation*) { return false; }
bool b_term(Sensation*) { return true; }
float a_value(Sensation*) { return 0.0; }
float b_value(Sensation*) { return 1.0; }

int main()
{
Sensation s;
MaxNode<a_term, a_value> a_node;
MaxNode<b_term, b_value> b_node;
std::cout << a_node.ValueOf(&s) << ' ' << b_node.ValueOf(&s) << '\n';
}
Jul 19 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Harry Pehkonen | last post by:
I have been defining new class methods when I'm trying to simplify some code. But I'm thinking I should just define functions within that method because they aren't useful from the outside anyway....
7
by: Bob Rock | last post by:
Hello, this may seem a strange question, but is there a way of being able to call methods of a class through an array of that class when not referencing a specific object in the array. In other...
8
by: johny smith | last post by:
If I have a simple class with say a couple of integers only is there any need for me to provide a destructor? thanks!
10
by: Joe Laughlin | last post by:
I'm sure there's a fairly easy answer for this... but how can I define a new type with range checking? Example: I want to define a new type that's like a double, except that you can only give...
5
by: Xiangliang Meng | last post by:
Hi, all. What are the benefit and the drawback of defining a class embedded inside another class? For example: class List { public:
5
by: Dale | last post by:
Is it possible to declare a method of an interface as static? For instance, can I create an interface that defines a static method and 2 instance methods?
2
by: Alex Feldman | last post by:
Which of the following is better? Defining an enum type inside a class as a nested type, or in the the namespace? An example of nested type enumerated type would be: public Class Product...
2
by: lcaamano | last post by:
We have a tracing decorator that automatically logs enter/exits to/from functions and methods and it also figures out by itself the function call arguments values and the class or module the...
9
by: Nick Maclaren | last post by:
I am defining a class, and I need to refer to that class when setting up its static data - don't ask - like this: Class weeble : wumpus = brinjal(weeble) Does anyone know how I can achieve...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.