optional interface

M

Milan

How do I write a class with "optional" interface like the following one:

class A
{
:
// inteface_a
// interface_b
};

void main()
{
A obj_a(interface_a); // define an object with interface a
A obj_b(interface_a | interface_b); // define an object with
interface a AND b

obj_b.func_b(); // calling function defined in interface
b; OK
obj_a.func_b(); // calling function not defined in
interface a; Compilation error
}

--

Can I write something like this in C++? Thanks.


Regards,
Milan.
 
E

ES Kim

Milan said:
How do I write a class with "optional" interface like the following one:

class A
{
:
// inteface_a
// interface_b
};

void main()

int main() according to the standard
{
A obj_a(interface_a); // define an object with interface a
A obj_b(interface_a | interface_b); // define an object with
interface a AND b

obj_b.func_b(); // calling function defined in interface
b; OK
obj_a.func_b(); // calling function not defined in
interface a; Compilation error
}

--

Can I write something like this in C++? Thanks.


Regards,
Milan.

Inheritance looks suitable.

class A
{
public:
void func_a();
virtual ~A();
};

class B : public A
{
public:
void func_b();
};

A obj_a;
B obj_b;

obj_a.func_b(); // illegal
obj_b.func_b();
obj_b.func_a(); // legal
 
V

Victor Bazarov

Milan said:
How do I write a class with "optional" interface like the following one:

class A
{
:
// inteface_a
// interface_b
};

void main()

int main()
{
A obj_a(interface_a); // define an object with interface a
A obj_b(interface_a | interface_b); // define an object with
interface a AND b

obj_b.func_b(); // calling function defined in interface
b; OK
obj_a.func_b(); // calling function not defined in
interface a; Compilation error
}

By using templates, I suppose. Something like

template<class a, class b = a> class A : public a, public b
{
};

// partial specialisation
template<class a> class A<a,a> : public a
{
};

struct interface_a
{
void func_a();
};

struct interface_b
{
void func_b();
};

int main()
{
A<interface_a> a_a;
A<interface_a, interface_b> a_ab;
a_a.func_a(); // OK
a_a.func_b(); // error
a_ab.func_b(); // OK
}

Victor
 
P

puppet_sock

[how do I? question]

Sure, use inheritance. Put the stuff that is common to all
types in the base. Put the specialized stuff in different
child types.

For extra credit, look up public, private, and protected
inheritance.
Socks
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,138
Messages
2,570,801
Members
47,347
Latest member
RebekahStu

Latest Threads

Top