Implementing virtual functions without the virtual keyword [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
My question is as follows:
I want (if it is possible) to "implement" virtual functions without using the "virtual" keyword (out of curiosity - I know the trick with functions pointers in C , I wish to do that in C++ !!).
My "idea" is to have a flag which will be assigned in the constructor in order to indicate which instance this object is.
My questions are:
1)Is it even possible ?
2)If so - what am I doing wrong ? or what is missing ?
I am using g++ which gives me these errors:
#‘B’ has not been declared
#‘C’ has not been declared
#class ‘B’ does not have any field named ‘flag’
#class ‘C’ does not have any field named ‘flag’
This is My suggestion:
#include <iostream>
using namespace std;
class A {
protected:
short flag;
public:
A(int f = 1) : flag(f) {}
void foo()
{
switch (this->flag)
{
case 1: cout << "A " << endl; break;
case 2: B :: foo(); break;
case 3: C :: foo(); break;
}
}
};
class B : public A{
public:
B(int f = 2) : A(f) {}
void foo() {cout << "B " << endl;}
};
class C : public B{
public:
C(int f = 3) : B(f) {}
void foo() {cout << "C " << endl;}
};
int main()
{
A a;
B b;
C c;
A *pb = &b;
A *pc = &c;
a.foo();
pb->foo();
pc->foo();
return 0;
} // end main
Thanks allot (!!) in advance , Guy.

Is it even possible ?
Yes. It may not be advisable, since it's more error-prone than virtual functions, and requires the base class to know about all of the derived classes, but it's certainly possible, and you're almost there.
If so - what am I doing wrong ?
You'll need to move the definition of A::foo out of the class, after the definitions of B and C, so that it can use those classes.
You'll need an explicit downcast to access member functions of derived classes:
static_cast<B*>(this)->foo();

Related

Private inheritance causing problem in c++ [duplicate]

This question already has answers here:
private inheritance
(6 answers)
What is the difference between public, private, and protected inheritance in C++?
(16 answers)
Closed 3 years ago.
Why would the following code run into error of ‘A’ is an inaccessible base of ‘B’? Here's my thoughts:
whenever we call function foo(), it will execute new B(5), which will first call the constructor of its base struct A.
struct A's constructor function is a public method, hence it should be accessible by its derived struct B (as protected if i'm not wrong).
then struct B's constructor function will be call to create a vector with five 0s.
then deleting object a will call destructor B, then destructor A.
Is there anything wrong with my logic? Your answer will be greatly appreciated
#include <iostream>
#include <vector>
using namespace std;
struct A
{
A() { cout << "Constructor A called"<< endl;}
virtual ~A() { cout << "Denstructor A called"<< endl;}
};
struct B : private A
{
vector<double> v;
B(int n) : v(n) { cout << "Constructor B called"<< endl;}
~ B() { cout << "Denstructor B called"<< endl;}
};
int main()
{
const A *a = new B(5);
delete a;
return 0;
}
There's nothing wrong with your logic, except that it's missing one point:
private inheritance basically means that only the inheriting class (B in this case) knows that it inherits from the base A.
That in turn means that only B can make use of all the privileges that come with this inheritance. One of these privileges is to be able to cast B* to A*. The function foo() doesn't know about B's inheritance, so it cannot perform that cast.
TL;DR
You are deriving B as 'private' from A. You must change it to
struct B : public A{
vector<double> v;
B(int n): v(n) {std::cout << "B Constructor" << std::endl};
~B() {std::cout << "B Destruktor" << std:.endl;};
};
Extended explanation
By using private inheritance you define B has a A instead of B is a A. With a has-a dependency you cannot up- and downcast between both classes (Apple cannot become a worm and vice versa. Even if an apple has a worm).
You mainly use private inheritance if you want to take advante of features implemented by another class, without exposing the public Inteface of the used class. For e.g. You could use features of a parser inside your class without being a parser on your own.

Function order not clear in C++? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am executing the below program in C++, but does not compile. Please help to find the issue
#include<iostream>
class A;
void showA(A& x) {
// Since showA() is a friend, it can access
// private members of A
std::cout << "A::a=" << x.a;
}
class A
{
int a;
public:
A() {a = 0;}
friend void showA(A& x); // global friend function
};
int main()
{
A a;
showA(a);
return 0;
}
It gives me below compilation error:
In function 'void showA(A&)':
7:27: error: invalid use of incomplete type 'class A'
:cout << "A::a=" << x.a;
^
3:7: note: forward declaration of 'class A'
class A;
^
class A;
void showA(A& x) {
// Since showA() is a friend, it can access
// private members of A
std::cout << "A::a=" << x.a;
}
We don't know that A will be a friend. We don't even know that A will have a member. You can not access members of an incomplete type. Trying to do so is invalid use of incomplete type.
Solution: Make the type complete (i.e. define the class) before accessing members.

C++ - unwanted use of base method [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a base class A and a few derived classes B, C and D, that all have a method DoSomething(), which is virtual in the base class method (it's implemented in all sub classes as well as in the base class).
I have a problem, that the derived class B uses the method from the base class A. This may be the result of bad design, but I do not see the problem as the implementation is pretty straight forward.
An object of class B that is created in the following
A* a = new B();
If I call the method DoSomething() for this object, the method of the base class is used:
a->DoSomething(); //Results in Base class method being called.
But I expect/want that the method of class B is used. Can you tell me what's wrong?
According to the symptoms that you describe:
either you have forgotten the virtual keyword in the base class member definition.
or you have a subtle difference in you signature in the derived class.
The way forward would be to indicate in the derived class that the function is an override:
class A {
...
virtual void DoSometing();
};
class D : public A {
...
void DoSomething() override;
};
In this case, in case of mismatch you'll get a clear compiler error message.
The following example implements what you asked for.
#include <iostream>
class A
{
public:
virtual void DoSomething()
{
std::cout << "A::DoSomething" << std::endl;
}
};
class B : public A
{
public:
virtual void DoSomething()
{
std::cout << "B::DoSomething" << std::endl;
}
};
int main(int argc, char **argv)
{
A *a = new B();
a->DoSomething();
delete(a);
return 0;
}
Output:
B::DoSomething

Inheritance of private members [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
When asked if private members of class B are inherited by D, a class derived from B, people emphatically say: yes they are inherited but not accessible directly, only indirectly for instance via public methods in the base class. OK, but what is the difference between not being inherited and not being directly accessible? For instance class X (NOT derived from B) also has access to private members of B via public methods of B, even though X doesn't inherit anything from B.
what is the difference between
1) not being inherited and
2) being inherited and not being directly accessible.
what is not clear?
The difference is in the class layout.
struct B {
private: char buf[1024];
};
struct D : B { };
Here, sizeof(D) >= sizeof(B). It's still there, i.e. it's clearly inherited.
If the base class has virtual functions that can be overriden by the derived class, clearly this is an important difference to a class having access to a base class instance but not inheriting from it:
class B
{
public:
virtual ~B() {}
int get_a() const
{
do_something();
return a;
}
virtual void do_something() const
{
std::cout << "In B\n";
}
private:
int a{};
};
class D : public B
{
virtual void do_something() const
{
std::cout << "In D\n";
}
};
int main()
{
D d;
d.get_a();
}
If the base class does not have any virtual functions, then the usefulness of inheriting from it is less clear. In fact, it is perhaps best not to inherit from it (at least publicly) as the lack of a virtual destructor could cause some problems, and it should be made a member variable instead.

Declare in parent class and define in child [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
So, I have class called A with a prototyped function x. B, C, and D are deriving from A, so the derived classes are having function x also protyped.
Now I want that not every class has function x defined.
How is that possible in C++?
It's against the OOP principles. Inheritance means an is-a relationship. In your example, B, C and D are a kind of A. If A has method x, the others should have also.
If it's not true, x is not really a method of A (but one of it's descendants')
If x should be only accessible from A instead, make it private:
private: void x() {}
You might want to declare x as pure virtual function, e.g.:
virtual void x() = 0;
Making assumptions about what you are asking since every class that derives from A will have x defined. If what you are asking for is that classes B, C and D are implemented in terms of A (i.e. they will utilize the functions of A but cannot be considered an instance of A), you can specify protected or private inheritance of A in B,C, and D.
Example code with this approach might be:
#include <iostream>
class A
{
public:
void x()
{
std::cout << "Hello from A::x" << std::endl;
}
};
class B : protected A
{
public:
};
class C : protected A
{
public:
void x()
{
std::cout << "Hello from C::x" << std::endl;
}
};
class D : public A
{
public:
};
int main(int argc, char **argv)
{
//B instance_of_B;
//instance_of_B.x(); // Will cause a compiler error
C instance_of_C;
instance_of_C.x(); // Will print Hello from C::x
D instance_of_D;
instance_of_D.x(); // will print Hello from A::x
}