Is there any way I can call child method from parent class? - oop

I am building a game for cocos2d-x and want to call child class method from parent class.
class Parent {
*//do something
//How can i call method from subchild class here?*
}
class Child : Parent {
*//do something*
}
class SubChild : Child {
void functionToBeCalledFromParent();
}

I am building a game for cocos2d-x and want to call child class method from parent class
You can 1) declare the function In parent and define it in the child or 2) define it in parent and override it (re-define it) in child.

By using CRTP, your example
class Parent {
void callSubclassFunction() {
//How can i call method from subchild class here?
}
}
class Child : Parent {
}
class SubChild : Child {
void functionToBeCalledFromParent();
}
would turn into
#include <iostream>
template <typename TSubclass>
class Parent {
public:
void callSubclassFunction() {
static_cast<TSubclass*>(this)->functionToBeCalledFromParent();
}
};
template <typename TSubclass>
class Child : public Parent<TSubclass> {
};
class SubChild : public Child<SubChild> {
public:
void functionToBeCalledFromParent() {
std::cout << "SubChild!" << std::endl;
}
};
int main()
{
SubChild child;
child.callSubclassFunction();
}
Runnable at Coliru
Passing SubChild as template parameter to Child<> works because the typename is valid as soon it's declared, which it is just in front of the inheritance list divider :.
Using static_cast to "downcast" in Parent is completely benign here. If the subclass doesn't define the function called in Parent, the compilation will just fail.
This technique is called static or compile-time polymorphism and it's what the ATL and WTL are built upon. The oppsosite and perhaps more conventional method would be dynamic or runtime polymorphism and it's what you get with virtual functions.

Related

Method from mock object not being called

I have this code.
I have a real object, that is initialized with a mock object.
When I call a method from the real object that should call a method from the mock object, it doesn't call the method from the mock object, but from the base class.
Why doesn't it calls the method from the mock object, how could I fix this?
Thanks
class Parent
{
public:
virtual bool verify() const;
};
class MockParent : public Parent
{
public:
MOCK_METHOD(bool, verify, (), (const, override));
};
class MyObject
{
public:
MyObject(Parent parent) :_parent(parent) {}
Parent parent;
};
class Testclass : ::testing::Test
{
TestClass() : mockParent(), myObject(mockParent) {}
MyObject myObject;
MockParent mockParent;
};
TEST_F(Testclass , test1)
{
// here I assume that it should call the method from the mock
EXPECT_CALL(this->myObject.mockParent, verify()).WillOnce(testing::Return(true));
//call method from myObject that calls parent.verify
}
In order for the polymorphic call to trigger, you need to pass a pointer or a reference to the base class, not the base class directly:
class MyObject
{
public:
MyObject(Parent& parent) :_parent(parent) {}
private: // members are usually private
Parent& parent;
};
this will allow you to have the proper method being called. Also, please keep in mind that Parent should outlive MyObject (so that you will avoid the dangling reference error).
Some additional notes: it's best to keep a pure virtual base class:
class ParentBase
{
public:
virtual ~ParentBase() = default;
virtual bool verify() const = 0;
};
and have both Parent and ParentMock to inferit from ParentBase. This enforces better separation of concerns - your classes will then deal with interfaces, not implementations.

Class subclass type with a public method

I don't understand why in Subclass definition a public method is involved
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
Source code of the RecyclerView.ViewHolder
public abstract static class ViewHolder {
public ViewHolder(View itemView) {
if (itemView == null) {
throw new IllegalArgumentException("itemView may not be null");
}
this.itemView = itemView;
}
Your question is why does the following code appear to call a public method ViewHolder within RecylcerView. Here is your code, with a slight rename to make things clearer:
class MyClass(itemView: View) : RecyclerView.ViewHolder(itemView)
And what is missing from your description is showing the outer class:
class RecyclerView { // outer/containing class
static class ViewHolder { // nested class
public ViewHolder(ViewItem view) { // constructor
// ... constructor body
}
}
}
Now looking at that nesting, to talk about the ViewHolder class you need to reference it as RecyclerView.ViewHolder. Then if you want to construct an instance of that you must add the constructor parameters, for example in Java:
new RecyclerView.ViewHolder(view);
In Kotin when you descend from a class, your constructor must call the super constructor and the short hand for that is to do it in the declaration.
class MyClass(ViewItem view) : RecyclerView.ViewHolder(view) {
// ...class body
}
This says MyClass descends from ViewHolder which is a nested class of RecyclerView and the constructor parameter coming into MyClass constructor is being passed into the super constructor of ViewHolder.
This is the same as Java:
class MyClass extends RecyclerView.ViewHolder {
public MyClass(ViewItem view) {
super(view);
}
}
You can also import the nested static class directly, then drop the RecyclerView prefix, but it is a bit clearer to leave it.

Point to the function created in C# project from generic typename in C++/CLI

C++/CLI :
public interface class ITest{
public:
virtual void doSomething (){
}
}
public ref Base {
...........
...........
}
generic <typename T> where T : ITest
public ref Derived : Base{
public:
virtual void doNothing (){
}
}
public ref AnotherClass {
public:
generic<class T> where T : Base
static int justDoThis(){
//Problem!!
}
}
C# :
In C# there are two classes A and B. A inherits from the ITest and B inherits from Derived where A is used as the typename. Also, B has a private variable of type A. So, from main function AnotherClass.justDoThis<B>() is called where B is passed as the generic type.
"//Problem!!" Part :
Now I have to create a new instance of B in this section and also access the A which is private variable in B.
So if I take your paragraph of description of the C# code:
class A : ITest {}
class B : Derived<A>
{
private A someVariableOfTypeA;
}
class Program
{
void Main(string[] args)
{
AnotherClass.justDoThis<B>();
}
}
And the problem is that you want to do this:
public ref AnotherClass {
public:
generic<class T> where T : Base
static int justDoThis()
{
// Problem!!
Something^ actuallyB = gcnew Something();
A^ a = actuallyB->someVariableOfTypeA;
}
}
Issue #1: You can allow creation of new objects of the generic type by specifying gcnew as another generic constraint. (In C#, this would be new.) This will require that the generic type have a default (i.e., parameterless) constructor, which you can access with the normal gcnew.
generic<class T> where T : Base, gcnew
static int justDoThis()
{
T^ t = gcnew T();
}
Issue #2: You cannot access private variables within an object. That's what private means. If you want to give justDoThis access to the A object, then add an appropriate public method or property to Base. The method or property would return type ITest. You could also put that method/property on a new interface (perhaps named IHaveAnITestAccessorMethod), and add that as another generic constraint, and B satisfies all the constraints.
Note that it won't do any good to make the variable public on type B: justDoThis doesn't know about B, it only knows about T, which is a Base with a no parameter constructor.
Disclaimers:
I didn't check my syntax with a compiler.
Yes, you can do anything with reflection, but that's a bad design. Don't do that, fix your code the right way.

Can't reference C++/cx class from xaml? (UWP)

I have a C++ class in my application testclient:
namespace testclient{
namespace models{
ref class myclass sealed{
public:
myclass();
property String^ getstring
{
String^ get()
{
return string;
}
}
private:
String^ string = "test";
}}}
I want to bind a control to the property getstring, and from what little I understand of UWP XAML data binding, I have to include this in the top of the MainPage.xaml: xmlns:data="using:testclient.models Problem is, intellisense is telling me "Undefined namespace. The 'using' URI refers to a namespace called testclient.models that could not be found." What am I doing wrong?
EDIT: I've found the problem goes away when I put the class in Mainpage.Xaml.h, but I'd rather not do this...
Every binding consists of a binding target and a binding source. Typically, the target is a property of a control or other UI element, and the source is a property of a class instance.
If you want to use myclass as datasource to MainPage's UI elements, you need to make sure the instance of the myclass is accessible to MainPage. That's why your first version resulted in error. In order to modify mainPage.Xaml.h as little as possible, you could follow steps below by creating a separate file(I simplified the member of myclass for easy debugging):
1) Create myclass.h:
namespace TestClient{
namespace models{
public ref class myclass sealed
{
private:
int test = 1;
public:
myclass()
{
}
property int gettest
{
int get() { return test; };
}
};
}
}
2) in MainPage.h, add following:
#include "myclass.h"
namespace TestClient
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public ref class MainPage sealed
{
private:
TestClient::models::myclass myTest;
.......
}
.........
}
3) Then you can manipulate myclass data in mainPage.cpp as you want. Codes may be like below:
MainPage::MainPage()
{
InitializeComponent();
int i = this->myTest.gettest;
...........
}
Still I have a question: while so many namespace nested? Also you can find a sample about data binding here just for your reference.

Jackson mixin selection and inheritance

I have a problem with Jackson mixin and inheritance. I have two target classes, a parent and a child. For those two target classes I have defined two MixIn classes (interfaces) with no inheritance relationship with each other. I also tested with one MixIn interface extending the other but there was no difference in the outcome. When Jackson serializes the parent class it uses the correctly defined mixin for the serialization config and everything works well. However when Jackson serializes the child class it will use the parent class mixin definitions for serializing properties that exist in both the parent and the child class. Then it uses the child class mixin definitions for serializing the properties defined in the child class but not in the parent class. Now this probably has something to do with comparing the base classes or implementing interfaces in Jackson.
Now the question is that is there any way that I could instruct Jackson to use only the mixin definitions for the child class when serializing objects of the child class? And yes I would like to keep both the the mixin definitions in place for two separate use cases so just removing the parent class mixin mapping is not gonna solve my issue.
Example code and expected and actual output JSONs below.
Environment:
Jackson version 2.1.4
Tomcat version 7.0.34.0
Target classes and interfaces they implement:
public interface TestI {
public String getName();
}
public interface TestExtendI extends TestI {
public Integer getAge();
}
public class Test implements TestI {
String name;
public Test(String name) {
this.name = name;
}
#Override
public String getName() {
return name;
}
}
public class TestExtend extends Test implements TestExtendI {
private Integer age;
public TestExtend(String name) {
super(name);
}
public TestExtend(String name, Integer age) {
super(name);
this.age = age;
}
#Override
public Integer getAge() {
return age;
}
}
Mixins definitions
public interface TestMixIn {
#JsonProperty("base-name")
public String getName();
}
public interface TestExtendMixIn {
#JsonProperty("ext-name")
public String getName();
#JsonProperty("ext-age")
public Integer getAge();
}
If both mixins are added to the mapper the output JSON is:
{
"base-name": "5", // from parent class mixin definition
"ext-age": 50 // from child class mixin defition
}
With mixin for TestI.class commented everything works as expected and the output JSON is (this is what I would like to achieve):
{
"ext-name": "5", // from child class mixin defition
"ext-age": 50 // from child class mixin defition
}
Object mapper configuration
#Provider
#Produces(MediaType.APPLICATION_JSON)
public class JacksonObjectMapper implements ContextResolver<ObjectMapper> {
private ObjectMapper mapper;
public JacksonObjectMapper() {
mapper = new ObjectMapper();
mapper.addMixInAnnotations(TestI.class, TestMixIn.class);
mapper.addMixInAnnotations(TestExtendI.class, TestExtendMixIn.class);
}
public ObjectMapper getContext(Class<?> type) {
return this.mapper;
}
}
REST api for handling the request/response
#Path("api/test/{id}")
public class TestRestApi {
#GET
#Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public TestI getTest(#PathParam("id") String id) {
TestI ret = new TestExtend(id, 50);
return ret;
}
}
Solution
As described by pgelinas in the first response the solution to this problem is to define the methods that should be handled by the 'child' mixin again in the child interface. For the example code above that would mean changes to the TestExtendI interface:
public interface TestExtendI extends TestI {
public Integer getAge();
// override the method from the parent interface here
#Override
public String getName();
}
This will solve the issue and doesn't add too much boilerplate code to the solution. Moreover it will not change the interface contracts since the child interface already extends the parent interface.
This is a tricky one; the answer to your specific question is no, you cannot tell a child class to not use the Mixin applied to a parent class.
However, a simple solution to your problem here is to re-declare the getName() method in the TestExtendI interface. I believe MixIn annotation resolution doesn't follow the usual parent-child override (as is the case with normal annotations), but will instead prefer the MixIn that is applied to the class that declares the method. This might be a bug in Jackson or a design choice, you can always fill an issue on github.