Difference between -> and . in C++ [duplicate] - constructor

This question already has answers here:
What is the 'this' pointer?
(8 answers)
How do the "->" and "." member access operations differ in C
(10 answers)
Closed 2 years ago.
I'm new to C++, I want to understand why I can't use the dot (.) operator here, since the variable is declared inside the class.
class SessionController {
private: SessionView view;
private: Session model;
public: SessionController (SessionView view, Session model) {
this.view = view;
this->model = model;
}
};
I'm getting an error at this.view = view; saying
Member reference type 'SessionController *' is a pointer; did you mean to use '->'?

In this case you can avoid the problem by setting the values directly in the initialiser list.
class SessionController {
private: SessionView view;
private: Session model;
public: SessionController (SessionView view, Session model) : view(view), model(model) {
}
};
Or if you really need to do it in the body.
class SessionController {
private: SessionView view;
private: Session model;
public: SessionController (SessionView pview, Session pmodel) {
view = pview;
model = pmodel;
}
};

Related

overwrite getter of es6 class instance [duplicate]

This question already has answers here:
Lazy getter doesn't work in classes
(3 answers)
Closed 4 years ago.
In this example I try to overwrite getter with cached value.
it doesn't works.
Is it possible to overwrite getter of a class instance?
class Module {
constructor(id) {
this.id = id
}
get element() {
const elm = document.getElementById(id)
if(!elm) throw new Error(`#${id} is not in document`)
delete this.element;
this.element = elm;
return elm;
}
}
You should use Object.defineProperty():
class Module {
constructor(id) {
this.id = id
}
get element() {
const elm = document.getElementById(this.id)
if(!elm) throw new Error(`#${id} is not in document`)
Object.defineProperty(this, 'element', {
value: elm,
});
return elm;
}
}

call function of class on instance of class

I have some code that generates answers based on the user input. But in somecases i need to update the values later by calling SetAnswers But when i compile my code i get the following error:
NullReferenceException: Object reference not set to an instance of an object
I get this error on the line marked by the arrow.
See below for my code:
public class Generate_Questions : MonoBehaviour{
public Question q5, q4;
void Start(){
q4 = create_question("Select object to edit", EXTERNAL);
Visual_Question vq1 = new Visual_Question(1, q4, new vector(1,1,1), Ui, Canvas);
vq1.draw_question();
}
void Update(){
}
public class Visual_Question : Generate_Questions{
public Visual_Question(int order_id, Question q, Vector2 loc, Dictionary<string, RectTransform> ui, RectTransform canvas){
}
public void draw_question(){
q4.SetAnswers(new Answer[]{ <--------- this generates the error.
new Answer(null, "Select an option")
});
}
}
public class Question{
public string text;
public int answers_loc;
public List<Answer> answers;
public Question(string q_text, int answers_loc){
answers = new List<Answer>();
this.text = q_text;
this.answers_loc = answers_loc;
}
public void SetAnswers(Answer[] c_answers){
foreach(Answer answer in c_answers){
this.answers.Add(answer);
}
}
public bool CheckIfAnswersAvailable(){
if(answers.Count > 0){
return true;
}else{
return false;
}
}
public int QuestionLocation(){
return answers_loc;
}
}
public Question create_question(string text, int a_type){
Question Q = new Question(text, a_type);
return Q;
}
public interface IAnswer{
string GetText();
string GetDataType();
object GetValue();
Question GetNextQuestion();
}
public class Answer : IAnswer{
public string text;
public Question next = null;
public int? action = null;
public Element obj = null;
public string property = null;
public float? value = null;
public Answer(Question next, string text){
this.text = text;
this.next = next;
}
public Answer(Question next, string text, Element obj, int? action){
this.action = action;
this.text = text;
this.next = next;
this.obj = obj;
}
public Answer(Question next, string text, Element obj, int? action, string property, float? value){
this.action = action;
this.next = next;
this.text = text;
this.obj = obj;
this.property = property;
this.value = value;
}
public string GetText(){
return text;
}
public string GetDataType(){
throw new System.NotImplementedException();
}
public object GetValue(){
return value;
}
public Question GetNextQuestion(){
return next;
}
}
}
how would i go about fixing this problem? I am a complete newbie to c#. So my question may be already answered but i just dont know what i am looking for.
I assume that IAnswer[] is an interface and since you are trying to initialize an abstract object you get that runtime exception
NullReferenceException: Object reference not set to an instance of an object
if you want to create instance of IAnswer object you have to restructure it like class or structure.
Your class Visual_Question derives from Generate_Questions, so the member q4 that you use en draw_question is not initialized. This is not the member of Generated_Questions but a member of Visual_Question that is not initialized.
In Generate_Questions you are creating a new instance of Visual_Question and then immediately calling draw_question on that new instance. You now have 2 instances of a question (both derive from Generate_Questions), but only one of them has had the Start method, which initializes q4 called. If, however, you attempt to call Start from your second instance, you're going to find yourself in an infinite series of recursive calls and quickly crash with a different error (a stack overflow in this case).
One issue with the current code is that Generate_Questions sounds more like an action than a class. I'd suggest removing the inheritance from Visual_Question and make that an interface that you would implement on Question. Question should probably have the create_question method removed. That probably belongs in a MonoBehavior script (technically it's a factory method -- look up the factory pattern -- I'm not going to go into it here since this is a beginner topic).
Something like (obviously not complete):
public class Generate_Questions : MonoBehaviour
{
private IVisualQuestion q4;
void Start()
{
q4 = new Question("Select object to edit", EXTERNAL);
q4.DrawQuestion(new vector(1,1,1), Ui, Canvas)
}
void Update() {}
}
public interface IVisualQuestion
{
void DrawQuestion(Vector2 loc, Dictionary<string, RectTransform> ui, RectTransform canvas);
}
public class Question : IVisualQuestion
{
// ... insert the Question constructor and code here ...
// Implement VisualQuestion interface
public void DrawQuestion(Vector2 loc, Dictionary<string, RectTransform> ui, RectTransform canvas)
{
this.SetAnswers(new Answer[]{new Answer(null, "Select an option")});
}
}
In general, you probably don't need inheritance. As you learn more C#, you'll discover that when inheritance is going to help it will be clear. More often than not, using an interface is a far better and flexible approach. As a commenter noted, you probably don't want to inherit from MonoBehavior. You really only need that for classes that the Unity Engine is going to directly handle.
Another note: the convention in C# is to name methods, variables, etc. in PascalCase, not using underscores to separate words.

How to initialize c++/cx class with aggregate initialization?

I have this ref class:
namespace N
{
public ref class S sealed
{
public:
property Platform::String^ x;
};
}
How do I initialize it in place with the aggregate initializer?
I have tried:
N::S s1 = { %Platform::String(L"text") };
but the compiler says
error C2440: 'initializing': cannot convert from 'initializer list' to
'N::S'
Also:
N::S s1 { %Platform::String(L"text") };
and the error is:
error C2664: 'N::S::S(const N::S %)': cannot convert argument 1 from
'Platform::String ^' to 'const N::S %'
This works greatly with the standard c++ like this:
struct T
{
wstring x;
};
T x { L"test" };
I do not want to use a constructor here.
I assume you mean you don't want a public constructor on the projected WinRT type -- no problem, you can use the internal keyword to mean "public inside C++ but not exposed through interop". That means you can even use native C++ types for your parameters if you like:
namespace Testing
{
public ref class MyTest sealed
{
public:
property String^ Foo {
String^ get() { return m_foo; }
void set(String^ value) { m_foo = value; }
}
internal:
// Would not compile if it was public, since wchar_t* isn't valid
MyTest(const wchar_t* value) { m_foo = ref new String(value); }
private:
String^ m_foo;
};
}
MainPage::MainPage()
{
// Projected type does NOT have this constructor
Testing::MyTest t{ L"Hello" };
OutputDebugString(t.Foo->Data());
t.Foo = "\nChanged";
OutputDebugString(t.Foo->Data());
}
Also you don't need to have the private variable to hold the string -- you could just use the auto-property as in your original code -- but I prefer to be explicit. It also means that if you needed to access the string a lot from within your C++ code you could provide an internal accessor function and not have to go through a vtable call to get at it.

How can I do asynchrous database in JavaFX [duplicate]

This question already has answers here:
JavaFX - Background Thread for SQL Query
(2 answers)
Closed 8 years ago.
I have a question. How can I do asynchrous database in JavaFX. I know that exist SwingWoker but I read that I can't use this in JavaFX. I read about Task but I can do convert the result to ObservableList but I need normal LinkedList.
I'm trying conntect to mysql database
I know that this forum has a lot of answering about database in javafx but all results are converted to ObservableList
Thank you for all the answers.
FlightControllerTask.java
public class FlightControllerTask extends Task<LinkedList<Flight>>{
private final static int MAX=10000;
ArrayList<Airport> airportList=new ArrayList<>()
#Override
protected LinkedList<Flight> call() throws Exception {
for (int i = 0; i < MAX; i++) {
updateProgress(i, MAX);
Thread.sleep(5);
}
LinkedList<Flight> flightList = new LinkedList<>();
Connection c ;
c = DBConnector.connect();
String SQL = "SELECT flight.idflight, airport.nameAirport, airport.nameAirport, flight.departureTime FROM flight INNER JOIN airport";
ResultSet rs = c.createStatement().executeQuery(SQL);
while(rs.next()){
flightList.add(new Flight(rs.getInt("idflight"), rs.getString("flightFrom"), rs.getString("flightTo"), rs.getTime("departureTime")));
}
return flightList;
}
FlightControllerService
public class FlightControllerService extends Service<LinkedList<Flight>>{
#Override
protected Task<LinkedList<Flight>> createTask() {
return new FlightControllerTask();
}
}
MainController.java
final FlightControllerService service= new FlightControllerService();
ReadOnlyObjectProperty<LinkedList<Flight>> flightList =service.valueProperty();
flightList.get();
public class FlightControllerTask extends Task<LinkedList<Flight>>{
#Override
protected LinkedList<Flight> call() throws Exception {
// load data
return data;
}
}
// usage:
FlightControllerTask task = new FlightControllerTask();
task.setOnSucceeded(ev -> task.getValue());
new Thread(task).start();
Now the part with task.getValue() is the crucial part, with this method you can retrieve the value that was computed with the task as soon as is is ready (thus the succeeded hook).

About factory constructor in Dart [duplicate]

This question already has an answer here:
Dart factory constructor - how is it different to “const” constructor
(1 answer)
Closed 8 years ago.
Below is about a usage of factory constructor from Seth Ladd's blog ' Dart - Trying to understand the value of 'factory' constructor'.
class Symbol {
final String name;
static Map<String, Symbol> _cache = new Map<String, Symbol>();
factory Symbol(String name) {
if (_cache.containsKey(name)) {
return _cache[name];
} else {
final symbol = new Symbol._internal(name);
_cache[name] = symbol;
return symbol;
}
}
Symbol._internal(this.name);
}
main() {
var x = new Symbol('X');
var alsoX = new Symbol('X');
print(identical(x, alsoX)); // true
}
IMHO, with general constructor, the same effect can be achieved with a subtle difference, but quite simpler.
class Symbol {
static final Map<String, Symbol> cache = {};
final String name;
Symbol(name) {
cache[name] = new Symbol._internal();
}
Symbol._internal();
}
main(){
var a = new Symbol('something');
var b = new Symbol('something');
print(identical(a, b)); // false!
print(Symbol.cache); //{something: Instance of 'Symbol'}
}
As shown above, though the two instances, a & b, are different objects, the effect is all the same as shown in 'print(Symbol.cache); //{something: Instance of 'Symbol'}' as a map object permit only one of same strings as its key.
So, my question was what are peculiar merits of factory constructor(or factory pattern) over general/const constructors? Because the above sample code alone shows no merit of factory constructor.
Could anyone explain what is so called 'Factory Pattern' in Dart language rather than Java/C#?
The factory PATTERN is the same. It's a general pattern and is not language specific.
Dart provides factory constructors to support the factory pattern. The factory constructor is able to return values (objects). In your first example you check if there is an instance for the key you return it.
In the second example you don't check the key of the map and you don't return the instance. That's why the two instances are not identical.
Regards,
Robert