Array of a type with different types inside - arduino-c++

I'm creating an Array of a Class Type (Button), and I want to have a subclass of it called ButtonMb inside the array Button
Is that possible?
I tried to have two different constructors and use only one Class, but since number of parameters are the same, I couln't reach anywhere.
Here is my code:
for simplicity I only included header code for class declaration
typedef void (*Callback)(void);
typedef int (*CallbackInt)(void);
class Button {
public:
OneButton _pin;
Button(uint8_t pin, Callback click=NULL, Callback longCl=NULL, Callback dblCl=NULL);
void loop();
};
class ButtonMb : public Button {
public:
CallbackInt _pinState;
ButtonMb(CallbackInt pinState, Callback click=NULL, Callback longCl=NULL, Callback dblCl=NULL);
void loop();
};
Button buttons[2] = {
Button(14),
ButtonMb([](){return slaves[0].getState("A15");)
};
Any help?
NOTE: I'm using Arduino, so code can be limited.

Instead of using array of objects, you can create array of pointers. Pointers of base class can point to derived classes, so you can have pointers to objects of different types in one array.

Related

How Composition (aka association) is another means of achieving re-use?

How can an object inside another object and the first object re-use the code behind the composed object And what is mean by composed object can be determined at run-time?
class Calculator
{
private:
long double operand_1;
long double operand_2;
long double result;
int optr;
int multiplier;
Button One;
//Button Two..
//..through Nine
Button Zero;
}
class Button
{
private:
int x1;
int y1;
int x2;
int y2;
char Label[55];
public:
Button( );
int hit( );
void show( );
void press( );
void select( );
}
I don't know whether I'm going in the right direction or not, I wanted to know the meaning of "composed object can be determined at Run-time?"
Here Button is composed in calculator class
This principle is demonstrated in Effective Java Book as 'Item 16'. I think when it is said "Favor Composition over Inheritance for code reuse", 'Composition' word is used as synonym of 'Containment' or 'association' and not in the spirit of true composition of UML. "Effective Java" by Joshua Bloch, provides good example under 'Item 16'.
In the demo example in above book, instance for containment (Subclass of Set) is passed through constructor and could always be cached outside (by client) breaking the composition. In book's demo as well it is case of containment and not a pure Composition (where composed object is not known outside).
Code reuse can be achieved by two mechanisms namely 'Inheritance (White box)' and 'Containment (Black box)'. In case of black box reuse, we (can) couple the reusable class at run time by assigning an instance of child class against a reference of Abstract base class/ Interface. In principle Inheritance should be used only when there is 'IsA' relationship and we want to use objects interchangeability and obtain the advantages of polymorphic behavior.
In your example though Calculator is using Button, its not expecting dynamic child class instances. But when we say addActionListener(), Button class will be making use of ActionListener by Containment as 'Button Is NOT a Kind of ActionListener" instead Button 'uses' ActionListener.
Here is an example of code reuse by Composition. Observe that instance of List is not known from outside the PackOfCards, but internally PackOfCards is delegating all functionality to Concrete List. When the Object of PackOfCards is destroyed, List also gets destroyed. But here we will not be able to change the concrete List dynamically from outside due to 'composition'.
public class Card {
public enum Suit{SPADE, HEART,DIAMOND,CLUB}
public enum Rank{ACE,QUEEN,KING}// and others
private Suit suit;
private Rank rank;
public Card(Suit suit, Rank rank) {
this.suit = suit;
this.rank = rank;
}
}
public class PackOfCards {
private List<Card> cards;
public PackOfCards() {
cards = new LinkedList<Card>();
}
public Card getCard(int index){
return cards.get(index);
}
public void shuffle(){
Collections.shuffle(cards);
}
// other methods
}

Different function definition after compilation

I have my Keyboard class:
namespace BSGameFramework
{
namespace Input
{
static public ref class Keyboard
{
public:
static KeyboardState GetState();
};
}
}
Where KeyboardState is a ref struct.
After compilation as dll from my C# application I see the function from metadata as follow:
namespace BSGameFramework.Input
{
public class Keyboard
{
public Keyboard();
public static void GetState(ref KeyboardState value);
}
}
Keyboard class has lost its static state and the function GetState is now returning void and taking a KeyboardState as referenced parameter!
Somebody know why? Thanks in advance :D
The reason is because of the return type, ref struct KeyboardState.
In C++/CLI, the "ref" vs. "value" is the thing that determines whether a type is a reference type or a value type, not "class" vs. "struct". ref class and ref struct are both the same thing as C#'s class. value class and value struct are both the same thing as C#'s struct.
Therefore, you have a C++/CLI method declared as returning a reference type, but without the ^. This data type does exist in C++/CLI, but not in C#. The method signature you see is a workaround.
There are two possible solutions to this issue:
Change KeyboardState to a value struct. From what you said, it sounds like you intended for this to be a value type from the beginning, so this is probably the best solution.
Change the return type of the method to KeyboardState^. This will let the method show up in C# the same as it does in C++/CLI. However, if you do this, you'll want to switch all uses of KeyboardState to KeyboardState^. It's a reference type, it should be used with a ^.

Cannot use managed event/objects in unmanaged code error c3265, c2811

Native C++ library that I am using in C++/CLI project raises events giving me results,
If I try to handle the event by extending the unmanaged event, it says the ref class can only extend ref class.
I then tried to create a native event but have manged object inside it to collect the results, but I get the error cannot declare managed object in unmanaged class.
Is there anyway to get it done in one of the ways I am trying, or should I declare unmanaged result objects fill them in unmanaged event and then Marshall it ?
Edit:
class MyNativeListener: public NativeEventListener
{
private:
ManagedResultsObject ^_results;
public:
void onEndProcessing(ProcessingEvent *event)
{
_results.Value = event->value;
//Many more properties to capture
}
};
This is what I am trying, I have extended the native event listener to capture the event, but not sure how to capture the results to a managed object.
Edit2
Found this while searching on the same line as suggested by #mcdave auto_gcroot
Your native class needs to store a handle to the managed object instead of a reference to it. You can do this using the gcroot template. If you dig into the gcroot template you will find it uses the GCHandle Structure, which with appropriate static casting can be stored as a void* pointer and so provides a means of storing managed references in native code.
Try expanding your code along the following lines:
#include <vcclr.h>
class MyNativeListener: public NativeEventListener
{
private:
gcroot<ManagedResultsObject^> _results;
public:
void onEndProcessing(ProcessingEvent *event)
{
_results->Value = event->value;
//Many more properties to capture
}
};

RTTI ?? create multiple object at runtime wxwidgets?

hi
sorry for my stupid question
what are the right way to create multiple control object from a list of array of label of object ...?
thank
The function wxCreateDynamicObject can be used to construct a new object of a given type, by supplying a string name. If you have a pointer to the wxClassInfo object instead, then you can simply call wxClassInfo::CreateObject.
You must include the IMPLEMENT_DYNAMIC_CLASS macro in every class you want to be able to dynamically create objects. IMPLEMENT_DYNAMIC_CLASS is a macro that not only initialises the static wxClassInfo member, but defines a global function capable of creating a dynamic object of the class in question.
Example
In a header file:
class wxFrame : public wxWindow
{
DECLARE_DYNAMIC_CLASS(wxFrame)
private:
wxString m_title;
public:
...
};
In a C++ file:
IMPLEMENT_DYNAMIC_CLASS(wxFrame, wxWindow)
wxFrame::wxFrame()
{
...
}

What is the use of making constructor private in a class?

Why should we make the constructor private in class? As we always need the constructor to be public.
Some reasons where you may need private constructor:
The constructor can only be accessed from static factory method inside the class itself. Singleton can also belong to this category.
A utility class, that only contains static methods.
By providing a private constructor you prevent class instances from being created in any place other than this very class. There are several use cases for providing such constructor.
A. Your class instances are created in a static method. The static method is then declared as public.
class MyClass()
{
private:
MyClass() { }
public:
static MyClass * CreateInstance() { return new MyClass(); }
};
B. Your class is a singleton. This means, not more than one instance of your class exists in the program.
class MyClass()
{
private:
MyClass() { }
public:
MyClass & Instance()
{
static MyClass * aGlobalInst = new MyClass();
return *aGlobalInst;
}
};
C. (Only applies to the upcoming C++0x standard) You have several constructors. Some of them are declared public, others private. For reducing code size, public constructors 'call' private constructors which in turn do all the work. Your public constructors are thus called delegating constructors:
class MyClass
{
public:
MyClass() : MyClass(2010, 1, 1) { }
private:
MyClass(int theYear, int theMonth, int theDay) { /* do real work */ }
};
D. You want to limit object copying (for example, because of using a shared resource):
class MyClass
{
SharedResource * myResource;
private:
MyClass(const MyClass & theOriginal) { }
};
E. Your class is a utility class. That means, it only contains static members. In this case, no object instance must ever be created in the program.
To leave a "back door" that allows another friend class/function to construct an object in a way forbidden to the user. An example that comes to mind would be a container constructing an iterator (C++):
Iterator Container::begin() { return Iterator(this->beginPtr_); }
// Iterator(pointer_type p) constructor is private,
// and Container is a friend of Iterator.
Everyone is stuck on the Singleton thing, wow.
Other things:
Stop people from creating your class on the stack; make private constructors and only hand back pointers via a factory method.
Preventing creating copys of the class (private copy constructor)
This can be very useful for a constructor that contains common code; private constructors can be called by other constructors, using the 'this(...);' notation. By making the common initialization code in a private (or protected) constructor, you are also making explicitly clear that it is called only during construction, which is not so if it were simply a method:
public class Point {
public Point() {
this(0,0); // call common constructor
}
private Point(int x,int y) {
m_x = x; m_y = y;
}
};
There are some instances where you might not want to use a public constructor; for example if you want a singleton class.
If you are writing an assembly used by 3rd parties there could be a number of internal classes that you only want created by your assembly and not to be instantiated by users of your assembly.
This ensures that you (the class with private constructor) control how the contructor is called.
An example : A static factory method on the class could return objects as the factory method choses to allocate them (like a singleton factory for example).
We can also have private constructor,
to enfore the object's creation by a specific class
only(For security reasons).
One way to do it is through having a friend class.
C++ example:
class ClientClass;
class SecureClass
{
private:
SecureClass(); // Constructor is private.
friend class ClientClass; // All methods in
//ClientClass have access to private
// & protected methods of SecureClass.
};
class ClientClass
{
public:
ClientClass();
SecureClass* CreateSecureClass()
{
return (new SecureClass()); // we can access
// constructor of
// SecureClass as
// ClientClass is friend
// of SecureClass.
}
};
Note: Note: Only ClientClass (since it is friend of SecureClass)
can call SecureClass's Constructor.
You shouldn't make the constructor private. Period. Make it protected, so you can extend the class if you need to.
Edit: I'm standing by that, no matter how many downvotes you throw at this.
You're cutting off the potential for future development on the code. If other users or programmers are really determined to extend the class, then they'll just change the constructor to protected in source or bytecode. You will have accomplished nothing besides to make their life a little harder. Include a warning in your constructor's comments, and leave it at that.
If it's a utility class, the simpler, more correct, and more elegant solution is to mark the whole class "static final" to prevent extension. It doesn't do any good to just mark the constructor private; a really determined user may always use reflection to obtain the constructor.
Valid uses:
One good use of a protected
constructor is to force use of static
factory methods, which allow you to
limit instantiation or pool & reuse
expensive resources (DB connections,
native resources).
Singletons (usually not good practice, but sometimes necessary)
when you do not want users to create instances of this class or create class that inherits this class, like the java.lang.math, all the function in this package is static, all the functions can be called without creating an instance of math, so the constructor is announce as static.
If it's private, then you can't call it ==> you can't instantiate the class. Useful in some cases, like a singleton.
There's a discussion and some more examples here.
I saw a question from you addressing the same issue.
Simply if you don't want to allow the others to create instances, then keep the constuctor within a limited scope. The practical application (An example) is the singleton pattern.
Constructor is private for some purpose like when you need to implement singleton or limit the number of object of a class.
For instance in singleton implementation we have to make the constructor private
#include<iostream>
using namespace std;
class singletonClass
{
static int i;
static singletonClass* instance;
public:
static singletonClass* createInstance()
{
if(i==0)
{
instance =new singletonClass;
i=1;
}
return instance;
}
void test()
{
cout<<"successfully created instance";
}
};
int singletonClass::i=0;
singletonClass* singletonClass::instance=NULL;
int main()
{
singletonClass *temp=singletonClass::createInstance();//////return instance!!!
temp->test();
}
Again if you want to limit the object creation upto 10 then use the following
#include<iostream>
using namespace std;
class singletonClass
{
static int i;
static singletonClass* instance;
public:
static singletonClass* createInstance()
{
if(i<10)
{
instance =new singletonClass;
i++;
cout<<"created";
}
return instance;
}
};
int singletonClass::i=0;
singletonClass* singletonClass::instance=NULL;
int main()
{
singletonClass *temp=singletonClass::createInstance();//return an instance
singletonClass *temp1=singletonClass::createInstance();///return another instance
}
Thanks
You can have more than one constructor. C++ provides a default constructor and a default copy constructor if you don't provide one explicitly. Suppose you have a class that can only be constructed using some parameterized constructor. Maybe it initialized variables. If a user then uses this class without that constructor, they can cause no end of problems. A good general rule: If the default implementation is not valid, make both the default and copy constructor private and don't provide an implementation:
class C
{
public:
C(int x);
private:
C();
C(const C &);
};
Use the compiler to prevent users from using the object with the default constructors that are not valid.
Quoting from Effective Java, you can have a class with private constructor to have a utility class that defines constants (as static final fields).
(EDIT: As per the comment this is something which might be applicable only with Java, I'm unaware if this construct is applicable/needed in other OO languages (say C++))
An example as below:
public class Constants {
private Contants():
public static final int ADDRESS_UNIT = 32;
...
}
EDIT_1:
Again, below explanation is applicable in Java : (and referring from the book, Effective Java)
An instantiation of utility class like the one below ,though not harmful, doesn't serve
any purpose since they are not designed to be instantiated.
For example, say there is no private Constructor for class Constants.
A code chunk like below is valid but doesn't better convey intention of
the user of Constants class
unit = (this.length)/new Constants().ADDRESS_UNIT;
in contrast with code like
unit = (this.length)/Constants.ADDRESS_UNIT;
Also I think a private constructor conveys the intention of the designer of the Constants
(say) class better.
Java provides a default parameterless public constructor if no constructor
is provided, and if your intention is to prevent instantiation then a private constructor is
needed.
One cannot mark a top level class static and even a final class can be instantiated.
Utility classes could have private constructors. Users of the classes should not be able to instantiate these classes:
public final class UtilityClass {
private UtilityClass() {}
public static utilityMethod1() {
...
}
}
You may want to prevent a class to be instantiated freely. See the singleton design pattern as an example. In order to guarantee the uniqueness, you can't let anyone create an instance of it :-)
One of the important use is in SingleTon class
class Person
{
private Person()
{
//Its private, Hense cannot be Instantiated
}
public static Person GetInstance()
{
//return new instance of Person
// In here I will be able to access private constructor
}
};
Its also suitable, If your class has only static methods. i.e nobody needs to instantiate your class
It's really one obvious reason: you want to build an object, but it's not practical to do it (in term of interface) within the constructor.
The Factory example is quite obvious, let me demonstrate the Named Constructor idiom.
Say I have a class Complex which can represent a complex number.
class Complex { public: Complex(double,double); .... };
The question is: does the constructor expects the real and imaginary parts, or does it expects the norm and angle (polar coordinates) ?
I can change the interface to make it easier:
class Complex
{
public:
static Complex Regular(double, double = 0.0f);
static Complex Polar(double, double = 0.0f);
private:
Complex(double, double);
}; // class Complex
This is called the Named Constructor idiom: the class can only be built from scratch by explicitly stating which constructor we wish to use.
It's a special case of many construction methods. The Design Patterns provide a good number of ways to build object: Builder, Factory, Abstract Factory, ... and a private constructor will ensure that the user is properly constrained.
In addition to the better-known uses…
To implement the Method Object pattern, which I’d summarize as:
“Private constructor, public static method”
“Object for implementation, function for interface”
If you want to implement a function using an object, and the object is not useful outside of doing a one-off computation (by a method call), then you have a Throwaway Object. You can encapsulate the object creation and method call in a static method, preventing this common anti-pattern:
z = new A(x,y).call();
…replacing it with a (namespaced) function call:
z = A.f(x,y);
The caller never needs to know or care that you’re using an object internally, yielding a cleaner interface, and preventing garbage from the object hanging around or incorrect use of the object.
For example, if you want to break up a computation across methods foo, bar, and zork, for example to share state without having to pass many values in and out of functions, you could implement it as follows:
class A {
public static Z f(x, y) {
A a = new A(x, y);
a.foo();
a.bar();
return a.zork();
}
private A(X x, Y y) { /* ... */ };
}
This Method Object pattern is given in Smalltalk Best Practice Patterns, Kent Beck, pages 34–37, where it is the last step of a refactoring pattern, ending:
Replace the original method with one that creates an instance of the new class, constructed with the parameters and receiver of the original method, and invokes “compute”.
This differs significantly from the other examples here: the class is instantiable (unlike a utility class), but the instances are private (unlike factory methods, including singletons etc.), and can live on the stack, since they never escape.
This pattern is very useful in bottoms-up OOP, where objects are used to simplify low-level implementation, but are not necessarily exposed externally, and contrasts with the top-down OOP that is often presented and begins with high-level interfaces.
Sometimes is useful if you want to control how and when (and how many) instances of an object are created.
Among others, used in patterns:
Singleton pattern
Builder pattern
On use of private constructors could also be to increase readability/maintainability in the face of domain-driven design.
From "Microsoft .NET - Architecing Applications for the Enterprise, 2nd Edition":
var request = new OrderRequest(1234);
Quote, "There are two problems here. First, when looking at the code, one can hardly guess what’s going
on. An instance of OrderRequest is being created, but why and using which data? What’s 1234? This
leads to the second problem: you are violating the ubiquitous language of the bounded context. The
language probably says something like this: a customer can issue an order request and is allowed to
specify a purchase ID. If that’s the case, here’s a better way to get a new OrderRequest instance:"
var request = OrderRequest.CreateForCustomer(1234);
where
private OrderRequest() { ... }
public OrderRequest CreateForCustomer (int customerId)
{
var request = new OrderRequest();
...
return request;
}
I'm not advocating this for every single class, but for the above DDD scenario I think it makes perfect sense to prevent a direct creation of a new object.
If you create a private constructor you need to create the object inside the class
enter code here#include<iostream>
//factory method
using namespace std;
class Test
{
private:
Test(){
cout<<"Object created"<<endl;
}
public:
static Test* m1(){
Test *t = new Test();
return t;
}
void m2(){
cout<<"m2-Test"<<endl;
}
};
int main(){
Test *t = Test::m1();
t->m2();
return 0;
}