How to call constructor and variables from another class? - class

I have a main class:
class Sportist{
private:
string ime;
int godina_na_ragjanje;
int godisna_zarabotuvacka_EUR;
public:
Sportist(string i, int g_n_r, int g_z_EUR){
ime = i;
godina_na_ragjanje = g_n_r;
godisna_zarabotuvacka_EUR = g_z_EUR;
}
};
And now I have a new class like this:
class Fudbaler:public Sportist{
private:
int broj_na_odigrani_natprevari;
int danocna_stapka;
public:
Fudbaler(string ime, int godina, int zarabotuvacka, int b, int d){
:Sportist(ime, godina, zarabotuvacka)
broj_na_odigrani_natprevari = b;
danocna_stapka = d;
}
float danok(){
return godisna_zarabotuvacka_EUR * danocna_stapka;
}
friend ostream& operator<<(ostream &os, Fudbaler F){
return os << "Ime: " << ime << endl
<< "Godina na raganje: " << godina_na_ragjanje << endl
<< "Godisna zarabotuvacka(EUR): " << godisna_zarabotuvacka_EUR << endl
<< "Danok sto treba da plati: " << danok();
}
};
I want to call the constructor from the first class in the second class, but I get errors that I haven't provided arguments which I do.. and also, I want to know how to access the private elements from the first class in the second, because it's taken as 'public', so how can I use them in my functions, like danok().
Errors while calling the constructor:
no matching function for call to 'Sportist::Sportist()'
candidates are:
Sportist::Sportist(std::string, int, int)
candidate expects 3 arguments, 0 provided
Error while calling variables using public method:
'int Sportist::godisna_zarabotuvacka_EUR' is private

You do not initialize Sportist before you enter your Fudbaler constructor function body. Therefore the Compiler tries to use a default constructur of Sportist which does not exists.
You Need to initialize Sportist before entering the Fudbaler constructor body.
Initializers are appended after the closing parenthesis before the function body in curly brackets:
Fudbaler(string ime, int godina, int zarabotuvacka, int b, int d)
: Sportist(ime, godina, zarabotuvacka),
broj_na_odigrani_natprevari(b),
danocna_stapka(d)
{
}
Private variables are private and cannot be accessed in child classes.
If you want to Access the Sportist members in Fudbaler member function you need to declare them protected (only accessible in this class and child classes) or public (generally accessible).

Related

flutter how to create an dart:ffi struct reference

I created a struct with dart:ffi.
import 'dart:ffi';
import 'package:ffi/ffi.dart';
class TestStruct extends Struct{
external Pointer<Utf8> strText;
#Int32()
external int nNum;
#Bool()
external bool bIsTrue;
//contstruct
TestStruct(String str, int number, bool state){
strText = str as Pointer<Utf8>;
nNum = number as int;
bIsTrue = state as bool;
}
}
I want to create a reference of TestStruct and use it. So I wrote the code.
TestStruct test = TestStruct("Text", 10, true);
but this is an error
Subclasses of 'Struct' and 'Union' are backed by native memory, and can't be instantiated by a generative constructor.
Try allocating it via allocation, or load from a 'Pointer'.
I tried searching with the api documentation, but I didn't understand. Do you know how to create a struct as a reference?? thank you.
Example:
class InAddr extends Struct {
factory InAddr.allocate(int sAddr) =>
calloc<InAddr>().ref
..sAddr = sAddr;
#Uint32()
external int sAddr;
}
You can allocate this with calloc function
final Pointer<InAddr> inAddress = calloc<InAddr>();
And free the pointer with
calloc.free(inAddress);
While I am late to the party, writing a complete example so that it may be helpful for others new to the FFI scene.
If this is the dart representative struct (from C) -
import 'dart:ffi';
import 'package:ffi/ffi.dart';
class TestStruct extends Struct{
#Int32()
external int nNum;
#Bool()
external bool bIsTrue;
// IMPORTANT: DO NOT DEFINE A CONSTRUCTOR since struct/union are natively allocated
}
You can instantiate from dart using ffi.Pointer like below.
// my_native_helper.dart
final dynamicLibrary = ... ; // load .so/process
void some_function() {
final Pointer<TestStruct > inAddress = calloc<TestStruct >();
inAddress.ref.nNum= 1234;
inAddress.ref.bIsTrue = false;
// ffigen generated method replicating C extern function
// To auto generate this, define the C signature in a header file
dynamicLibrary.receiveFromDart(inAddress);
calloc.free(inAddress);
}
The C method will look like below.
extern "C" void recieveFromDart(TestStruct* structPtr) {
cout << structPtr->nNum << "/" << structPtr->bIsTrue << endl;
}
According to the doc you can't create instances of Struct classes:
https://api.flutter.dev/flutter/dart-ffi/Struct-class.html
However, you typically would need pointers. So you can come up with something like that:
static Pointer<InAddr> allocate(int sAddr) {
final pointer = calloc<InAddr>();
pointer.ref.sAddr = sAddr;
return pointer;
}

Initialize a final variable in a constructor in Dart. Two ways but only one of them work? [duplicate]

This question already has an answer here:
Is there a difference in how member variables are initialized in Dart?
(1 answer)
Closed 1 year ago.
I'm trying to understand the following example where I try to initialize a final variable in a constructor.
1st example - works
void main() {
Test example = new Test(1,2);
print(example.a); //print gives 1
}
class Test
{
final int a;
int b;
Test(this.a, this.b);
}
2nd example doesn't work
void main() {
Test example = new Test(1,2);
print(example.a); //compiler throws an error
}
class Test
{
final int a;
int b;
Test(int a, int b){
this.a = a;
this.b = b;
}
}
and when i remove final then it works again
void main() {
Test example = new Test(1,2);
print(example.a); //print gives 1
}
class Test
{
int a;
int b;
Test(int a, int b){
this.a = a;
this.b = b;
}
}
what is the difference between the constructor in the 1st and the 2nd constructor why final initialization works with the first and doesn't with the 2nd.
Can anyone explain that to me please?
THanks
You cannot instantiate final fields in the constructor body.
Instance variables can be final, in which case they must be set exactly once. Initialize final, non-late instance variables at declaration, using a constructor parameter, or using a constructor’s initializer list:
Declare a constructor by creating a function with the same name as
its class (plus, optionally, an additional identifier as described in
Named constructors). The most common form of constructor, the
generative constructor, creates a new instance of a class
syntax in the constructor (described in https://www.dartlang.org/guides/language/language-tour#constructors):

C++ Accessing variables in a function in one class from a different class

I'm trying to code a program with multiple classes such the one of the class reads the variables from a text file and the other classes use these variables for further processing.
The problem I'm facing is that I'm having trouble passing the variables from one class to another class, I did try "friend" class and also tried to use constructors but failed
to get the desired output.
The best I could do was
suppose I have class 1 and class 2, and I have a variable "A=10" declared and initialised in class 1, with the help of constructor I inherit it in class 2;
when I print it in class 1, it gives a correct output as 10 but when I print it in class 2 it gives an output as 293e30 (address location)
Please guide me on how to this.
Class1
{
public:
membfunc()
{
int A;
A = 10;
}
}
Class2
{
public:
membfunc2()
{
int B;
B = A + 10;
}
membfunc3()
{
int C, D;
C = A + 10;
D = B + C;
}
}
If i print variables, i expect to get
A = 10, B = 20, C = 20, D = 40
But what I get is
A = 10, B=(252e30) + 10
I think your problem was that you were defining local variables in your member functions, instead of creating member variables of a class object.
Here is some code based on your sample to demonstrate how member variables work:
class Class1
{
public:
int A;
void membfunc()
{
A=10;
}
};
class Class2
{
public:
int B;
int C;
int D;
void membfunc2(Class1& class1Object)
{
B = class1Object.A + 10;
}
void membfunc3(Class1& class1Object)
{
C = class1Object.A + 10;
D = B + C;
}
};
(Full code sample here: http://ideone.com/cwZ6DM.)
You can learn more about member variables (properties and fields) here: http://www.cplusplus.com/doc/tutorial/classes/.

What are function typedefs / function-type aliases in Dart?

I have read the description, and I understand that it is a function-type alias.
A typedef, or function-type alias, gives a function type a name that you can use when declaring fields and return types. A typedef retains type information when a function type is assigned to a variable.
http://www.dartlang.org/docs/spec/latest/dart-language-specification.html#kix.yyd520hand9j
But how do I use it? Why declaring fields with a function-type? When do I use it? What problem does it solve?
I think I need one or two real code examples.
A common usage pattern of typedef in Dart is defining a callback interface. For example:
typedef void LoggerOutputFunction(String msg);
class Logger {
LoggerOutputFunction out;
Logger() {
out = print;
}
void log(String msg) {
out(msg);
}
}
void timestampLoggerOutputFunction(String msg) {
String timeStamp = new Date.now().toString();
print('${timeStamp}: $msg');
}
void main() {
Logger l = new Logger();
l.log('Hello World');
l.out = timestampLoggerOutputFunction;
l.log('Hello World');
}
Running the above sample yields the following output:
Hello World
2012-09-22 10:19:15.139: Hello World
The typedef line says that LoggerOutputFunction takes a String parameter and returns void.
timestampLoggerOutputFunction matches that definition and thus can be assigned to the out field.
Let me know if you need another example.
Dart 1.24 introduces a new typedef syntax to also support generic functions. The previous syntax is still supported.
typedef F = List<T> Function<T>(T);
For more details see https://github.com/dart-lang/sdk/blob/master/docs/language/informal/generic-function-type-alias.md
Function types can also be specified inline
void foo<T, S>(T Function(int, S) aFunction) {...}
See also https://www.dartlang.org/guides/language/language-tour#typedefs
typedef LoggerOutputFunction = void Function(String msg);
this looks much more clear than previous version
Just slightly modified answer, according to the latest typedef syntax, The example could be updated to:
typedef LoggerOutputFunction = void Function(String msg);
class Logger {
LoggerOutputFunction out;
Logger() {
out = print;
}
void log(String msg) {
out(msg);
}
}
void timestampLoggerOutputFunction(String msg) {
String timeStamp = new Date.now().toString();
print('${timeStamp}: $msg');
}
void main() {
Logger l = new Logger();
l.log('Hello World');
l.out = timestampLoggerOutputFunction;
l.log('Hello World');
}
Typedef in Dart is used to create a user-defined function (alias) for other application functions,
Syntax: typedef function_name (parameters);
With the help of a typedef, we can also assign a variable to a function.
Syntax:typedef variable_name = function_name;
After assigning the variable, if we have to invoke it then we go as:
Syntax: variable_name(parameters);
Example:
// Defining alias name
typedef MainFunction(int a, int b);
functionOne(int a, int b) {
print("This is FunctionOne");
print("$a and $b are lucky numbers !!");
}
functionTwo(int a, int b) {
print("This is FunctionTwo");
print("$a + $b is equal to ${a + b}.");
}
// Main Function
void main() {
// use alias
MainFunction number = functionOne;
number(1, 2);
number = functionTwo;
// Calling number
number(3, 4);
}
Output:
This is FunctionOne
1 and 2 are lucky numbers !!
This is FunctionTwo
3 + 4 is equal to 7
Since dart version 2.13 you can use typedef not only with functions but with every object you want.
Eg this code is now perfectly valid:
typedef IntList = List<int>;
IntList il = [1, 2, 3];
For more details see updated info:
https://dart.dev/guides/language/language-tour#typedefs
https://www.tutorialspoint.com/dart_programming/dart_programming_typedef.htm
typedef ManyOperation(int firstNo , int secondNo); //function signature
Add(int firstNo,int second){
print("Add result is ${firstNo+second}");
}
Subtract(int firstNo,int second){
print("Subtract result is ${firstNo-second}");
}
Divide(int firstNo,int second){
print("Divide result is ${firstNo/second}");
}
Calculator(int a,int b ,ManyOperation oper){
print("Inside calculator");
oper(a,b);
}
main(){
Calculator(5,5,Add);
Calculator(5,5,Subtract);
Calculator(5,5,Divide);
}

Writing methods and constructors

OK, i need someone to explain to me where to start on this project.
First I need to overload the constructor by adding a default (no-args) constructor to Person that defines an object to have the name "N/A" and an id of -1.
Then i need to add a setter method named reset that can be used to reset the two private instance variables of this class to two values passed in as parameters.
Then I need to add a getter method named getName and getId that can be used to retrieve these two private variables
Here is the code:
public class Person
{
private String name;
private int id;
private static int personCount = 0;
// constructor
public Person(String pname)
{
name = pname;
personCount++;
id = 100 + personCount;
}
public String toString()
{
return "name: " + name + " id: " + id
+ " (Person count: " + personCount + ")";
}
// static/class method
public static int getCount()
{
return personCount;
}
////////////////////////////////////////////////
public class StaticTest
{
public static void main(String args[])
{
Person tom = new Person("Tom Jones");
System.out.println("Person.getCount(): " + Person.getCount());
System.out.println(tom);
System.out.println();
Person sue = new Person("Susan Top");
System.out.println("Person.getCount(): " + Person.getCount());
System.out.println(sue);
System.out.println("sue.getCount(): " + sue.getCount());
System.out.println();
Person fred = new Person("Fred Shoe");
System.out.println("Person.getCount(): " + Person.getCount());
System.out.println(fred);
System.out.println();
System.out.println("tom.getCount(): " + tom.getCount());
System.out.println("sue.getCount(): " + sue.getCount());
System.out.println("fred.getCount(): " + fred.getCount());
}
}
I'm not exactly sure where to start and I don't want just the answer. I'm looking for someone to explain this clearly.
First I need to overload the constructor by adding a default (no-args) constructor to Person that defines an object to have the name "N/A" and an id of -1.
Read about constructors here.
The Person class already contains a ctor that takes 1 argument. What you need to do is create a "default ctor" which is typically a ctor w/out any parameters.
Example:
class x
{
// ctor w/ parameter
//
x(int a)
{
// logic here
}
// default ctor (contains no parameter)
//
x()
{
// logic here
}
}
Then i need to add a setter method named reset that can be used to reset the two private instance variables of this class to two values passed in as parameters.
Setter methods are used to "encapsulate" member variables by "setting" their value via public function. See here.
Example:
class x
{
private int _number;
// Setter, used to set the value of '_number'
//
public void setNumber(int value)
{
_number = value;
}
}
Then I need to add a getter method named getName and getId that can be used to retrieve these two private variables
Getters do the opposite. Instead of "setting" the value of a private member variable, they are used to "get" the value from the member variable.
Example:
class x
{
private int _number;
// Getter, used to return the value of _number
//
public int getNumber()
{
return _number;
}
}
Hope this helps
I highly recommend consulting the Java Tutorials, which should be very helpful here. For example, there is a section on constructors which details how they work, even giving an example of a no-argument form:
Although Bicycle only has one constructor, it could have others, including a no-argument constructor:
public Bicycle() {
gear = 1;
cadence = 10;
speed = 0;
}
Bicycle yourBike = new Bicycle(); invokes the no-argument constructor to create a new Bicycle object called yourBike.
Similarly, there are sections dedicated to defining methods and passing information to them. There's even a section on returning values from your method.
Read the above and you should be able to complete your homework :-)