Incomplete type not allowed in C++ - class

I am trying to recreate the data type of array for experimental purposes. I created a class "node" with two attributes value(int) and nextvalue(node) to hold the next node. The plan was to chain a number of node objects together and create an array.
here is my code:
class node
{
public :int value;
node nextnode;
};
However, I get the following error in the line node nextnode; : incomplete type not allowed
Like it is some sort of "recursive class" if that even exists.
I have even tried creating a second class named "node2" that was the exact same with the previous one so as to trick the compiler int thinking the class didn't reference itself.
Is there a solution or is this a dead end?

Unlike other language (for instance C#) a class is always a value type, not a reference. So a class cannot have a member of the type of the same class (you would get infinite recursion and a class with infinite size). Also please note that in C++ class and struct are identical (except for the default access modifier)
So you need to use pointers:
#include <memory>
class node
{
public:
int value;
std::unique_ptr<node> nextnode;
};

Related

How to declare and init nested enum with reserved keyword as type name in Swift?

I'm having a hard time to figure out how to declare a certain nested enum and calling one of it's automatic constructors. This enum i'm trying to declare is supposed to have a reserved keyword as type name.
Here is a simplified example of what i'm trying to do:
import Foundation
public class Foo {}
public extension Foo {
enum `Type`: Int {
case bar
}
}
var type: Foo.`Type`
type = Foo.`Type`(rawValue: 0)
This doesn't compile in Swift 5.2 with error
error: type 'Foo.Type' has no member 'init'
I'm pretty sure it is just a matter of getting the syntax right but i just can't figure it out. Anyone can please explain how to do it or is it just impossible all together?
There is no way to do this specific thing you want to do. That's why nobody uses nested types named Type, even though we all want to—the language already provides this type, and you don't get to override it with your own. We all use the Objective-C style naming of just smashing the word Type right up there without a proper delimiter.
FooType is what you've got to work with.

Understanding OO class definition

This is an extract from IB Computer Science Higher Level Paper 2 November 2010, Q1b
I am trying to understand what are the “roles” of: “Node” and “item” in the following class definition
<< from question >>
class Node (1)
{
public int item; (2)
public Node next: (3)
public Node(int d) (4)
{
item = d; (5)
next = null; (5)
}
public void displaynode()
{
output(Item + “ “);
}
<< end of question extract >>
The numbers in parentheses after certain lines in the class definition are my references used in the questions below.
Is the following correct?
(1) Node is the name of the class which is used when I want to create a new, single Node by issuing
Node x = new Node(5)
which results in a new Node containing the value 5, stored in (4,5).
(2,3) These are data items with the labels item and next, of type integer (2) and Node (3) respectively (I don’t understand what it means to have type Node) ????
Being public can I access and alter the contents by using following references x.item, x.Node ???
(4) This is the method Node which accepts a single, integer parameter named d.
(5) The input parameter “d “ gets put in the object variable “item”, and “next” is set to the value Null when a new Node is created.
(1) Node is the name of the class which is used when I want to create a new, single Node by issuing Node x = new Node(5) which results in a new Node containing the value 5, stored in (4,5).
This is a reasonable explanation.
(2,3) These are data items with the labels item and next, of type integer (2) and Node (3) respectively (I don’t understand what it means to have type Node) ???? Being public can I access and alter the contents by using following references x.item, x.Node ???
Please call them variables rather than "data items". item and next are instance variables, and since next is of type Node, we can say that class Node is recursively defined. This an implementation of a linked list in which each element contains an integer value and a reference to the next element.
You're correct about the meaning of public.
(4) This is the method Node which accepts a single, integer parameter named d.
It's important that you recognize that this is a constructor method which is automatically called to initialize the state of a Node when it's instantiated.
(5) The input parameter “d “ gets put in the object variable “item”, and “next” is set to the value Null when a new Node is created.
I'd rather say the value of input parameter d gets assigned to the variable item. I wouldn't call it an object variable - in some languages, ints are considered objects, in others not. In some perspectives, variables themselves are seen as primitive objects, distinct from their values. Regardless, I think it detracts from the clarity to say "object variable".
For further study, look into the following distinctions:
Variable vs value: A variable is an element that holds a value. Variables allow us to write code that operate over different values. Values can be anything - numbers, text, arrays, records, objects, functions, and more, depending on the language.
Class vs object: A class is a blueprint for a state machine, while an object is a specific instance of one. Objects have state and methods which operate on that state.
Class vs type: A class declares what goes on inside a state machine. A type declares (what is known for) a set of values. Value types are associated with the operators that can be called on those types of values. Object types declare the methods that can be called on those types of objects (but not what those methods do).
In many OOP languages and discussions, class and type are conflated. Even variable and value are commonly conflated. As a computer scientist, you should know and understand the differences.

Mark Haxe Class for forced extend?

Is there a compiler meta for Class declaration, that prevents creating Class instance before extending it? In other words - some sort of opposite of #:final meta.
Like so (last line of code):
class A {
// ...
}
class B extends A {
// ...
}
// ...
var b = new B(); // OK
var a = new A(); // induce compiler-error
Simply don't declare a constructor at all for class A
Both the other answers are correct (no constructor or private constructor), but there are a few more details that you may interest you:
Here's an example of no constructor. Of note is that A simply doesn't have a constructor, and B simply doesn't call super(). Other than that, everything else works as you'd expect.
Here's an example of a private constructor. You still can't instantiate a new A(), but you do still need to call super() from B's constructor.
Technicalities:
Use of some features (like a default value on a member variable) will cause A to get an implicit constructor, automatically. Don't worry, this doesn't affect constructability or whether you need to call super(). But know that it is there, and if necessary an implicit super() call is prepended to B's constructor. See the JS output to verify this.
In any case, know that you can still instantiate an A at runtime with var a = Type.createInstance(A,[]); as compile-time type checks do not limit RTTI.
Related discussion:
Aside from private/no constructor, Haxe doesn't have a formal notion of abstract classes1 (base classes not expected to be instantiated) or abstract methods2 (functions on abstract base classes with no implementation that must be implemented by a derived class.) However, Andy Li wrote a macro for enforcing some of those concepts if you use them. Such a macro can detect violations of these rules and throw compile-time errors.
1. Not to be confused with Haxe abstracts types, which are an entirely different topic.
2. Not to be confused with virtual functions, which wikipedia describes as a function which can be overridden (though various docs for various languages describe this highly loaded term differently.)
One way of achieving this is to create private Class constructor:
class A {
private function new() {
// ...
}
}
// ...
var a = new A(); // Error: Cannot access private constructor

C++ Is "class Name*" a class pointer?

I was watching an unreal tutorial and encountered this line of code:
class UStaticMeshComponent* Pickup;
It is a forwards declaration.
I have been studying c++ for a while and have not encountered anything like this before. I know about pointers and references, but I never seen this format: class Name*. Are we creating a class pointer to another class? I tried searching for class names followed by a *, but the only result that appeared were about data types and pointers.
public:
APickUp ();
virtual void BeginPlay () override;
virtual void tick ( float DeltaSeconds );
private:
class UStaticMeshComponent* Pickup;
class UStaticMeshComponent* Pickup;
This declares the type class UStaticMeshComponent and also declares the variable Pickup of type pointer to UStaticMeshComponent. So the above code is more or less equivalent with:
class UStaticMeshComponent;
UStaticMeshComponent* Pickup;
Because at this point you don't have the definition of UStaticMeshComponent (just the declaration), UStaticMeshComponent is considered an incomplete type. There are a few things you can do with an incomplete type. One of them is declare pointers to them.
When you are only using a pointer to a type, the type is not required to be complete, so this works fine even if UStaticMeshComponent has not been defined. That means when this header is included in one of your cpp files, it should compile a bit faster than if Pickup.h were to include the header where UStaticMeshComponent is defined.
This speed up could be substantial depending on how big that header is, and how many times the include is avoided during compilation.
The big confusion here is the difference between:
class UStaticMeshComponent* Pickup;
and
class UStaticMeshComponent *Pickup;
and even this:
class UStaticMeshComponent * Pickup;
, as in the example http://www.cplusplus.com/doc/tutorial/classes/#pointers_to_classes .
The difference is - bad practice. All supposed to mean the same thing but only the second example is correct, yet all of them work.
At least according to this:
https://users.ece.cmu.edu/~eno/coding/CppCodingStandard.html
place the * close to variable name not pointer type
I am a novice, I might be wrong. Please correct me if i am wrong.

Access to undefined member variables when exposing a class in boost python

I'm struggling with some unwanted side effects of exposing a class in boost.python. It seems that in Python, it is legal to assign to a member variable that was never defined in the original class. So in the example below I define a class with a member 'a', but also writing to a member 'b' works in Python. This has the (in my case negative) side effect that I can't detect typos when accessing class members, since myClass.complicatedObjectName=1 works and myclass.complicatedObjectname=1 works as well, even if the latter variable is never defined. As illustration, when exposing a class like this
#include <boost/python.hpp>
using namespace boost::python;
class A {
public:
A() : a(1) {}
int a;
};
BOOST_PYTHON_MODULE(liba) {
class_<A>("A", init<>())
.def_readonly("a", &A::a);
}
and trying to acces A.a and A.b
import liba
myA = liba.A()
print "a", myA.a
myA.b = 1
print "b", myA.b
generates the output:
a 1
b 1
I would prefer the assignment 'myA.B = 1' to fail. Is there a way to make boost.python behave like this?
I'm sorry if this question is already asked somewhere, but I couldn't find an answer. Thanks for pointing me to existing answers if there is one.
I'm working with the standard boost libraries (v 1.54) on Ubuntu 14.04.
In python you can override _setattr_ to only allow attribute names from a defined list. Here is how to do that: https://stackoverflow.com/questions/3079306/how-to-protect-againt-typos-when-setting-value-for-class-members.
Then some ideas how to achieve the same in C++: How to override __setattr__ in a wrapped class (from C++)? and Catch creation of instance attributes of boost::python-wrapped classes from c++.