Using Derived function from base class [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
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.
Closed 8 years ago.
Improve this question
I have a class test_d which publicly inherits class test_b. The class test_d has a function getValues() which I need to call using an object of class test_b. I tried using dynamic_cast and reinterpret_cast but it didn't work. Is there any other way to do that?
class test_b {
// this is the base class
};
class test_d : public test_b {
// this is the derived class
public int getValues() const; // this is the function I need to use.
};
test_b* objB = new test_d;
dynamic_cast<test_d*>(objB)->getValues(); // this is what I am doing.

In your interface you should declare your method as pure virtual function and then in your derived class you should write an implementation
class test_b
{
public:
virtual int getValues() const = 0;
};
class test_d : public test_b
{
public:
virtual int getValues() const
{
return m_value;
}
};
And from somewhere of your main():
test_b* objB = new test_d;
objB->getValues();
this is the basics of OOP: the interface and an implementation of the interface

Related

Is it better to use polymorphism or storing data? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 days ago.
Improve this question
I have a question not only about c++, even though my example is about c++.
if I have a base class let's call it Mother and 2 childs, call respectively Child1 and Child2.
The classes have a method get_name.
My question is which version is better (pro/cons) between:
class Mother
{
virtual char* get_name() const = 0;
virtual ~Mother() = default;
}
class Child1: public Mother
{
virtual char* get_name() const override {return "child1";}
}
class Child2: public Mother
{
virtual char* get_name() const override {return "child2";}
}
and
class Mother
{
Mother(char* name): name(name) {}
char* get_name() const {return this->name;}
char* name;
}
class Child1: public Mother
{
Child1(): Mother("Child1") {}
}
class Child2: public Mother
{
Child1(): Mother("Child2") {}
}
In the first case I use polymorphism and in the second case I store the data (the name). I'd like to know the advantage(s) and disadvantage(s) of each methods.
Thank you
I tried to find an answer on internet but I haven't so far.
The first One is Polymorphism albeit wrong that goes for the second one as well(I'll explain it below), since you didn't inherit the Base Class Mother.
In the first case I use polymorphism and in the second case I store
the data (the name). I'd like to know the advantage(s) and
disadvantage(s) of each methods. Thank you
I'll Return the answer in a form of a Question, are you going to call the method through a Base Pointer? if yes, Do you want them to behave differently in each cases? Then you should use the concept of the polymorphism.
One of the Major advantage of Polymorphism is to have the Derived Classes behave differently using the Same Function name when called from a base pointer like below,Godbolt here..
#include <iostream>
class Base
{
public:
Base(){}
virtual ~Base(){}
virtual int SomeFunction(){ return 0;}
protected:
int m_nX;
int m_nY;
};
class Derived1 : public Base
{
public:
Derived1(int x, int y){m_nX = x; m_nY = y;}
~Derived1(){}
virtual int SomeFunction()
{
return m_nX * m_nY;
}
};
class Derived2 : public Base
{
public:
Derived2(int x, int y){m_nX = x; m_nY = y;}
~Derived2(){}
virtual int SomeFunction()
{
return m_nX + m_nY;
}
};
int main()
{
Derived1 bDerived1(10,10);
Derived2 bDerived2(10,10);
Base* bBase = &bDerived1;
printf("The Result of Some Function From Derived 1 is %d\n",bBase->SomeFunction());
bBase = &bDerived2;
printf("The Result of Some Function From Derived 2 is %d\n",bBase->SomeFunction());
return 0;
}
One of the biggest disadvantage is misuse, when a simple inheritance would do. Like you've said in your question. You can simply store the data since you are only fetching it and not doing anything differently.
The second code is wrong since you don't need to explicitly Construct the base class since it would be constructed automatically when a Derived Class is constructed using it's Default Constructor. What you would do is to either call up a function that set's a value to the base class member, or if you want it to be done During the object's construction, you can simply assign it inside the constructor itself. Like above.

How do I create a new object from an array which holds different objects in c++ [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 5 years ago.
Improve this question
I have a base class "A" and many derived classes, say "B", "C", "D".
I need to have an array which holds these objects (or pointers). I have a function which will take an index into this array and should create one of the objects (make new object) in the array. How do I do this ? Following is a snippet, showing just wrappers below.
class A
{
};
class B: public A
{
};
class C: public A{
};
class D: public A{
};
static A anArray[] = {B, C,D };
int main() {
`A anObject = myFunction(2);`
}
In the above code, when I call myFunction, I should be able to get a new D
There are many ways to achive this,
here's one way:
#include <memory>
class A {
public:
virtual ~A() = default; // important
};
class B: public A { };
class C: public A{ };
class D: public A{ };
static std::unique_ptr<A> anArray[] = {
std::make_unique<B>(),
std::make_unique<C>(),
std::make_unique<D>()
};

Why is this pure virtual method not compiling? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
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.
Improve this question
I use a pure virtual method as shown in the code below.
#include <iostream>
using namespace std;
class Advertisment
{
public:
vitual void price (int Uchrg, int no_of_unt) = 0;
{
}
};
class TVadvertisment : public Advertisment
{
public:
void price (int Uchrg, int no_of_unt)
{
int adPrice = Uchrg * no_of_unt;
cout << "Advertisment Price: " << adPrice;
}
};
int main()
{
TVadvertisment T;
T.price(1000, 60);
return 0;
}
As I know a pure virtual function will be declared as virtual void display() = 0;. But the Code::Blocks compiler show an error because of this = 0. Without that it will compile successfully.
And also I didn't use pointers to call methods of derived class.
Your function is pure virtual, which means the method is virtual and not even implemented in the base class (= 0).
So you have to delete the block after it.
It has to be:
virtual price(int Uchrg, int no_of_unt) = 0;
without the { }.
Virtual means, that classes that inherit from a base class can override the method and called via the base class interface. If a class has a pure virtual method, the class is abstract and this function needs to be overridden by classes that inherit from that base class to be instantiated.
In short:
Virtual:
virtual price(int Uchrg, int no_of_unt)
{
// Implementation
}
Has an implementation is the base class. Sub classes does not need to override, but they can. The class is not abstract and can be instanciated.
Pure virtual:
virtual price(int Uchrg, int no_of_unt) = 0; // No implementation
There is no implementation, the sub classes must override this to be not abstract.
Call a virtual method via base class:
Base* pBase = new Derived;
pBase->fun();
The method is called via the interface of the base class, but it will be the derived class' method.

OOP Problems C++ [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 6 years ago.
Improve this question
what is wrong? I think, it's correctly
class A{
public:
virtual bool isGun() = 0;
virtual bool isArmor() = 0;
};
class B: public A{
public:
virtual bool isGun(){ return true; }
};
int main(){
B* b = new B;
}
A::isArmor() - defined is other class
I realy need to define all pure virtual functions in all child-classes?
what is wrong?
You haven't defined isArmor in B so you can't create any instances of B.
I realy need to define all pure virtual functions in all child-classes?
Yes. That is what a pure virtual function means. If you don't want to have to define a function in all child-classes then don't make it pure virtual.
You have to override the pure virtual function in your subclass otherwise your subclass will become abstract class and hence we cannot create object of abstract class.
If you do not want isArmor function in subclass to expose, override it as private so that client of B cannot use it.
class B : public A{
private:
virtual bool isArmor() { return true; } // Like this
public:
virtual bool isGun(){ return true; }
};

Throw an exception or return default value in base class [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have a base class that defines methods as virtual and those methods has nothing inside, just the declaration. I have a class that derives from the base class and doesn't implements all the methods and here is where the problem appears. If we call a method that isn't implemented on the derived class, but in the base, it crashes.
Example (it crashes):
#include <iostream>
class Foo
{
public:
virtual std::string ref() {}
};
class Bar : public Foo {};
int main(int argc, char ** argv)
{
auto foo = new Bar;
auto bar = foo->ref();
return 0;
}
Q: What is the best solution in this case.
1) - Return a default (empty) value.
virtual std::string ref()
{
return "";
}
2) - Throw an exception that you can't call methods directly from the base class.
virtual std::string ref()
{
throw std::runtime_error(":(");
}
Thank you.
This is what pure virtuals are for:
virtual std::string ref() = 0;
now the compiler won't let you instantiate an instance of a derived type that doesn't define that function.
If we call a method that isn't implemented on the derived class, but
in the base, it crashes.
This does not strictly apply to your example code:
virtual std::string ref() {}
An implementation is there; you get a crash because the implementation doesn't return anything. The same would likely happen here, for example:
#include <string>
std::string f() {}
int main()
{
std::string x = f();
x = "";
}
(I say "likely" because it's undefined behaviour, so the crash is not guaranteed.)
As for your problem:
If you need to call functions which do not conceptually exist, then you have a design problem; chances are that your base class tries to fulfill too many responsibilities at the same time.
Otherwise, use abstract classes. You can make a class abstract by declaring at least one function pure virtual:
class Foo
{
public:
virtual std::string ref() = 0; // pure virtual function
};
Please note three further things:
You almost certainly need a virtual destructor in your base class.
Except of the destructor, consider making your public functions non-virtual and your virtual functions private, the public non-virtual ones calling the private virtual ones.
Your function looks like a candidate for a const function.
Final example:
class Foo
{
public:
virtual ~Foo() {}
std::string ref() const { return refImpl(); }
private:
virtual std::string refImpl() const = 0;
};