class wall_t {
...
};
class inlet_t {
...
};
class outlet_t {
...
};
class couple_t {
...
};
and I also defined
1 2 3
class block_t {
...
};
now I have a block, and I want this block to be one of those four boundary conditions, and I will tell which one it is when the programming is running(after compilation)
I will write this in my program,
1 2
cin>>boundary;
block_t block1(boundary);
if the boundary is wall, then I can get the variables and functions defined in wall_t, and the other boundary types' variables and functions are not exist at all.
How can I do this? How to define block_t and related using functions? Thanks.
Make block_t the parent class, and then have the other four inherit from it.
1 2 3 4 5
class block_t {/**/};
class wall_t : public block_t {/**/};
//etc
Tada, polymorphism.
*EDIT* You'll probably have to rework some of your design decisions. Passing boundary (whatever that is) to a ctor to determine which type is extremely sketch. I can help you figure things out further in the morning. zzzzzzZZZzzz
#include <typeinfo>
class block_t {
public:
block_t(void* object);
// ...
private:
void* _object;
enum { NOTYPE, WALL, INLET, OUTLET, COUPLE } _type;
};
block_t::block_t(void* object) : _object(object) {
if (object == nullptr)
_type = NOTYPE;
elseif (typeid(*object) == typeid(wall_t))
_type = WALL;
elseif (typeid(*object) == typeid(inlet_t))
_type = INLET;
elseif (typeid(*object) == typeid(outlet_t))
_type = OUTLET;
elseif (typeid(*object) == typeid(couple_t))
_type = COUPLE;
else
_type = NOTYPE;
}
// to use it:
switch (_type) {
case WALL: {
wall_t* obj = static_cast<wall_t*>(_object);
obj->doSomething();
// etc
} break;
// etc
}
// to set it...
block_t block1 (boundary); // Sets the type to whatever boundary is
I'm just posting this for completeness, because I have not seen this on the forum's before and I reckon it should be on here. However, this is complicated and slightly inefficient to implement, so you should definitely use polymorphism like @xismn said, unless there is a specific reason not to use, or this method would be easier to use.
Ugh, I'm sorry. The only example I could come up with was pretty much identical to NT3's.
The thing is, you will have to do either one of these things:
1.) Design your classes in such a way that member variables are the same and not unique to each class.
2.) Find a way to make pointer casting pretty.
This is typically where design patterns come in handy. In your case, I would look into the factory design pattern.
Now I have a program, I want to read in a random block, and I want to assign one of the three boundary condition to this block, and if Neumann_t is assigned, program will ask about the derivative value, how can I do that?