array and object declaration - list

I'm trying to create an array list of objects. I am a student and my professor requires that all declaration are before the executable code and that all instantiations or initializations (not sure which term) are done in the executable code. I'm new to the List or ArrayList concept and i can't quite figure out how to get this started.
List <Room> roomAry; //declare array object for rooms
//initialize room array
roomAry = new List<Room>();
This keeps telling me it can't compile.
The error follows:
List is abstract; cannot be instantiated roomAry = new List
();

Because it should be roomAry = new ArrayList<Room> (). It's correct for both .NET and JAVA.
List is just an interface (JAVA)

The error is telling you exactly what the problem is. The List is an interface and is thus abstract. You cannot create an instance of an abstract class or an interface; you always have to create an instance of a concrete class.
Please see the All Known Implementing Classes: section under the List interface in the javadocs. (Note that if the implementing class itself is abstract, then you cannot use it)
So you can use one of the implementing classes for the instantiation. One of the simpler ones is ArrayList.
roomAry = new ArrayList<Room>();

Related

C++ design issue. New to templates

I'm fairly new to c++ templates.
I have a class whose constructor takes two arguments. It's a class that keeps a list of data -- it's actually a list of moves in a chess program.
I need to keep my original class as it's used in other places, but I now need to pass extra arguments to the class, and in doing so have a few extra private data members and specialize only one of the private methods -- everything else will stay the same. I don't think a derived class helps me here, as they aren't going to be similar objects, and also the private methods are called by the constructor and it will call the virtual method of the base class -- not the derived method.
So I guess templates are going to be my answer. Just looking for any hints about how might proceed.
Thanks in advance
Your guess is wrong. Templates are no more the answer for your problem than inheritance is.
As jtbandes said in comment below your question, use composition.
Create another class that contains an instance of your existing class as a member. Forward or delegate operations to that contained object as needed (i.e. a member function in your new class calls member functions of the contained object). Add other members as needed, and operations to work with them.
Write your new code to interact with the new class. When your new code needs to interact with your old code, pass the contained object (or a reference or a pointer to it) as needed.
You might choose to implement the container as a template, but that is an implementation choice, and depends on how you wish to reuse your container.
Templates are used when you want to pass at compile time parameter like values,typenames, or classes. Templates are used when you want to use exactly the same class with the same methods, but applying it to different parameters. The case you described is not this I think.
If they aren't goign to be similar objects you may want to create a specialized class (or collections of function) to use from the various other classes.
Moreover you can think of creating a base class and extending it as needed. Using a virtual private method should allow you to select the method implementation of the object at runtime instead of the method of the base class.
We may help you more if you specify what does they need to share, what does your classes have in common?
The bare bones of my present code looks like this:
class move_list{
public:
move_list(const position& pos, unsigned char ply):pos_(pos),ply_(ply){
//Calculates moves and calls add_moves(ply,target_bitboard,flags) for each move
}
//Some access functions etc...
private:
//private variables
void add_moves(char,Bitboard,movflags);
};
Add_moves places the moves on a vector in no particular order as they are generated. My new class however, is exactly the same except it requires extra data:
move_list(const position& pos, unsigned char ply,trans_table& TT,killers& kill,history& hist):pos_(pos),ply_(ply),TT_(TT),kill_(kill),hist_(hist) {
and the function add_moves needs to be changed to use the extra data to place the moves in order as it receives them. Everything else is the same. I guess I could just write an extra method to sort the list after they have all been generated, but from previous experience, sorting the list as it receives it has been quicker.

Proxy class for polymorphic type, using templates

This is for a "game engine" as a bit of programming practice. All of my GameObjects are component based, where each component adds a functionality to its parent GameObject and all of these components descend from a base Component class which has virtual methods making it polymorphic.
When I read in these gameobject definitions from an XML file some components need to know about others for example a physics component needs to be aware of the transform component for the physics calculations. However if these components aren't present in the XML file then occasionally it throws up nasty null-pointers and endless rabbit hole call stack chasing to find the XML typo I fudged while half asleep.
My solution was to have a node in the XML file as an assertion that a component of this type should exist and possibly throw an exception or another appropriate action if it doesnt.
Eg.
<ComponentRequirement type="ComponentTransform">myTransformComponent</ComponentRequirement>
So I need a way of representing this in C++. The first idea, template classes to change according to what type of component it's the proxy of since this class needs to act like their unproxied component. I've solved that with some operator overloading so long as the class is a template class.
template <class T>
class ComponentRequirement {
public:
T* operator->() { (I chose the arrow operator because the CompReq class will never be referenced as a pointer)
return this->component;
}
//Other unrelated functions . . .
private:
T* component;
};
And this is all fine and dandy at compile time because I can just say
ComponentRequirement<ComponentTransform> req = ComponentRequirement("myComponentTransform");
But I need to be able to specify what that template type in place of the will be from a string when I read the XML in. I thought a hashmap could do it but I dont think the type name even "is" anything other than a human readable compiler hint so I couldn't use it as a hashmap value.
Can this be done and how could I go about implementing it? Inserting some string literal into a "black-box of magic" and get something that can be used as a template argument. And if it helps, everything that will be the value of "T" is polymorphic.
Or is there a better solution to my problem. It needs to be able to act as any Component I put into it and it needs to be discernable at runtime.
EDIT 1:
In my components I have a read and write function. If I read the component requirement in there I can make sure the template has the right value because each component is seperate.
I can then evaluate the requirements with a virtual function and a few functions in the gameobject class to check it's a valid configuration. This could solve the problem.
At a first glance I would use the factory pattern for your problem. That way you can create classes to create your objects given a different string without specifying the exact class you need at compile time unlike with normal typed constructors. The analogy I see people use are Virtual Constructors.
http://www.oodesign.com/factory-pattern.html
In essence you would have a map of factories (creator objects).
Define some top level interface for your components, such as IComponent.
Define a factory class for every component you want to generate that has a Create Instance method. I recommend the Create Instance method should be part of an interface like IFactory.
During setup of your program create your map and assign factories to particular keys. ActorCreator["MyComponent"] = new MyComponentFactory();
When you want to create an object read from an XML node you can just call the create instance method on the returned factory for the key. auto myComponent = ActorCreator[readXML]->CreateInstance();
You now have an actor/components whose concrete type has been decided at runtime instead of compile time.

What's the difference between a List and a LinkedList?

What is the difference ?
List list = new List();
LinkedList Llist;
list.add(anyString); for example and Llist.AddFirst(anyString);
In which language? In Java (and probably also the language you use) List is just an interface for various types of Lists. You can have single linked lists, double linked lists, circular lists etc.
In Java:
List is an interface, it does not provide a concrete implementation but only the definition of which operations are possible for classes implementing this interface. I.e. each implementation of List must provide a size() method returning the number of elements in the list.
LinkedList is a concrete implementation. It supports all the methods of List (probably some more, specific to its implementation). As the name suggests, it is implementing the interface using the linked list approach.
A different List implementation would be ArrayList, which is internally using an array to implement the interface.
In C#:
In C# the naming is different. List is a concrete implementation of IList. Therefore IList is the interface, and List is the ArrayList implementation. There is also a LinkedList in C#.
First of all, you need to understand Interface and Implementation class in Java.
List is interface and LinkedList is concrete class implementing List interface.
new keyword and constructor symbol () is used to instantiate (create object) for concrete classes, but cannot be used for Interface
List list = new List(); //cannot compile as List is Interface
List list = new ArrayList(); //Valid and can compile
List list = new LinkedList(); //Valid and can compile
Before you go deep into java.util.Collection package, you should learn basic Java well.
Assuming Java.in java there are many libraries that we can work from each has its own objects
so List belong to java.awt library while LinkedList belongs to java.util.
about add and addFirst()
I think the difference will be like this
list.add(A)
list.add(B)
list.addFirst(C)
if you printed the list you will find the order is C A B
hope it helped

C++ Extending an Array Class (OOP)

Is it possible to derive a child from an array Class?
What I am playing with right now is:
Creating an array of Linked Lists
I am building a List class from which I can derive different types of lists (ie. Linear, Circular, Double Linked, etc...
What I would like to do is to extend an array class to make a "arrayOfLists" class. Then I would take the child class and add to it a LinkedList object member.
Is this possible? Am I even thinking of OOP correctly in this instance?
Thank you for your help
The fact that you're talking about it as an arrayOfLists class is a pretty good clue that inheritance is the wrong tool for this job.
Inheritance (public inheritance, anyway) should only be used when the derived class can be substituted for the base class under any possible circumstances. In other words, that an arrayOfLists could be used anywhere a List could be used. Although that might be possible, it seems fairly unlikely.
It sounds to me like what you want is really just an array-like template (e.g., std::vector) instantiated over one of your linked list classes.

A list containing objects of two different classes in C++

I feel more fluent in Java than C++ so I will try to explain what I want to "transport" in a few words. In Java you could create an ArrayList containing objects of 2 or more classes that one of them inherited from another. Let me illustrate. Let's say we have:
class Vehicle
{
...
}
class Car extends Vehicle
{
...
}
You could then do something like that Car a = new Vehicle ([arguments]);
And then you could add objects of both Vehicle and Car to the same ArrayList created as following:
ArrayList ar = new ArrayList<Car>();
Now to my problem, in C++ I have manually written the code to create a simple linked list. Each node of this list is described below:
struct clientListNode
{
vip* cust;
struct clientListNode* next;
};
vip is another class which is derived from customer.Is there any way to allow my list to accept both objects of vip class and customer class?
Polymorphism works the other way. You can use a customer* pointer to point to a vip object, but not the other way. (This is related to the Liskov-substitution principle.)
So if you had a customer* in your clientListNode class, it would accept both vip* and customer* pointers.
However, I don't think you should reinvent the wheel and implement a linked list from the ground. You should look into the STL (Standard Template Library) which already has solutions for problems like this. For instance, it already has an implementation of the linked list, std::list.
You have to template std::list with the base type you'd like to use it with, but it is important that you cannot use the type directly as a value (std::list<cust>), because that would physically store cust instances in memory, in which you cannot fit the more specific vip type (slicing would occur).
Instead you have to use some kind of handle as the template parameter, you can use a native pointer (std::list<cust*>), but that way you have to manage memory deallocation, or - more preferably - you can use a smart pointer, like shared_ptr (std::list<std::shared_ptr<cust>>), that way the created objects are going to get destroyed automatically.
I doubt you could make Car = new Vehicle even in java, but the other way around makes sense.
What you're after is called "polymorphic collection". C++ standard lib does not have one out of the box, but you can approximate it with a collection of shared_ptr<Vehicle> s or unique_ptr<Vehicle> s. The former would fork very close to a java equivalent.
3rd party libraries may have ready to use polymorphic collections, you can use the term for search.
If customer is the base class, then the cust field of the node should be of type customer*, and it will gladly accept both customers and vips.