How to make variable in companion object protected - kotlin

I want to make a variable in companion object protected. I think when I make the variable protected, it would be accessible only from another class which inherit the variable's class, not from other classes or functions. But It doesn't work.
Here's my code
open class Population{
companion object{
#JvmStatic // Though I added it because of recommendation of IntelliJ, It still doesn't work.
protected var population_quantity: Int = 0
}
}
class Marin : Population(){
init{
population_quantity += 1 // I want to make it possible
}
}
class Checker : Population() {
fun printPopulationQuantity()
{
println(population_quantity) // I also want to make it possible
}
}
fun main(){
var m1 = Marin()
var checker = Checker()
// But I want to make codes below here impossible
// Population.population_quantity += 1
// println(Population.population_quantity)
}
Below is what I want to make which is made via C++. I hope below would clarify what I'm saying.
#include <iostream>
class Population
{
protected:
static int population_quantity;
};
int Population::population_quantity = 0;
class Marin : Population
{
public:
Marin()
{
std::cout << "Marin is generated" << std::endl;
population_quantity += 1;
}
~Marin()
{
std::cout << "Marin is dead" << std::endl;
population_quantity -= 1;
}
};
class Checker : Population
{
public:
void printPopulationQuantity()
{
std::cout << population_quantity << std::endl;
}
};
int main()
{
Checker checker;
checker.printPopulationQuantity();
Marin *m1 = new Marin();
checker.printPopulationQuantity();
// std::cout << "population : " << Population::population_quantity << std::endl;
// Can't access population_quantity from main which doesn't inherite Population
// because Population::population_qantity is protected.
// But it is possible to access Population:population_quantity from Marin which inherits Population.
delete m1;
checker.printPopulationQuantity();
return 0;
}
When you help me solve this problem, I'm sure that I would feel sincere thankful from bottom of my heart.

That is probably because in class Checker : Population you have a void function which is in public.
Try changing it to this:
class Checker : Population
{
protected:
void printPopulationQuantity()
{
std::cout << population_quantity << std::endl;
}
};

Related

passing a class variable to API function

I want to track a global variable that I am passing into an API function. I found that one could do it using a class:
template <class T>
class MonitoredVariable
{
public:
MonitoredVariable() {}
MonitoredVariable(const T& value) : m_value(value) {}
//T operator T() const { return m_value; }
const MonitoredVariable& operator = (const T& value)
{
PlugIn::gResultOut << "value changed " << std::endl;
m_value = value;
return *this;
}
private:
T m_value;
};
The API function takes variables as
bool APIFunction(double time, bool *is_done, double *fraction_done);
The following gives me an error:
ImagePtr Im;
bool is_done;
MonitoredVariable<double*> fraction_done;
bool frameready = Im->APIFunction(2.1, is_done, fraction_done);
ERROR:
error C2664: cannot convert argument 3 from 'MonitoredVariable<double *>' to 'double *'
what would I have to change here?
thx!
I'm not really sure if this is what you want:
#include <iostream>
using namespace std;
template <class T>
class MonitoredVariable
{
public:
MonitoredVariable() {}
MonitoredVariable(const T& value) : m_value(value) {}
//T operator T() const { return m_value; }
const MonitoredVariable& operator = (const T& value)
{
//PlugIn::gResultOut << "value changed " << std::endl;
m_value = value.m_value;
return *this;
}
void printValue() {
std::cout << m_value;
}
T& getValue() {
return m_value;
}
private:
T m_value;
};
bool func(double firstDouble, bool *is_done, double* fraction_done) {
// do stuff
*fraction_done = firstDouble + (40.23 * 5);
*is_done = true;
return true;
}
int main()
{
bool is_done = true;
MonitoredVariable<double> fraction_done;
func(2.10, &is_done, &fraction_done.getValue());
fraction_done.printValue();
return 0;
}
So basically we have a Class called MonitoredVariable which has a variable called m_value. I'm not really sure why you wanted it to be a pointer, because we can also take the address of a normal double variable.
In the following it makes perhaps more sense what I want to achieve. I want to input a class variable into an API function and monitor the variable in real time. This value goes from zero to 1 every 3 ms or so. Yet I try to avoid using while loop and track it within the class with overloaded = operator.
#include "stdafx.h"
#include <iostream>
#include <thread>
#include <future>
using namespace std;
template <class T>
class MonitoredVariable
{
public:
MonitoredVariable() {}
MonitoredVariable(const T& value) : m_value(value) {}
void printValue() {
std::cout << m_value;
}
const MonitoredVariable& operator = (const T& value)
{
m_value = value.m_value;
if(m_value> 0.8) std::cout << m_value; // *THIS NEVER GETS PRINTED!!!*
return *this;
}
T& getValue() {
return m_value;
}
private:
T m_value;
};
bool func(bool *is_done, double* fraction_done) {
unsigned long c = 1;
while (*is_done)
{
*fraction_done = (double) 0.01*c;
this_thread::sleep_for(chrono::milliseconds(10));
c++;
if (*fraction_done >= 1) *is_done = false;
}
return true;
}
int main()
{
bool is_done = true;
MonitoredVariable<double> *MonitoredVariablePtr = new MonitoredVariable<double>();
std::future<bool> fu = std::async(std::launch::async,func, &is_done, &MonitoredVariablePtr->getValue());
// IF I UNCOMMENT THIS, IT PRINTS...
/*
while(is_done)
{
if(MonitoredVariablePtr->getValue() > 0.8) MonitoredVariablePtr->printValue();
}
*/
return 0;
}
Why does not the (if(m_value> 0.8) std::cout << m_value) line within the class never gets printed when the value is updated?
THX!

How to clear the std::map<K,V*> container and delete all the pointed objects safely?

None of the standard library containers will call delete on contained raw pointers. I have checked for a solution on SO for C++98 but have not found the answer.
I have created template <typename K, typename V> void clearAndDestroy( std::map<K, V*> *&myMap) as a replacement function for std::clear() (remove all elements and call the destructors).
It works for maps with pointers to objects std::map(key,V*). The function works also for cases when map contains same V* pointers for the different keys.
#include <iostream>
#include <map>
#include <string>
#include <set>
using namespace std;
// clearAndDestroy deletes all objects and remove them from the std::map(K,V*) container.
template <typename K, typename V>
void clearAndDestroy( std::map<K, V*> *&myMap)
{
if(myMap == NULL)
return;
std::set<V*> mySet;
typename std::map<K,V*>::iterator itr;
typename std::set<V*>::iterator sitr;
itr = myMap->begin();
while (itr != myMap->end()) {
mySet.insert(itr->second);
++itr;
}
sitr = mySet.begin();
while (sitr != mySet.end()) {
delete(*sitr);
++sitr;
}
myMap->clear();
}
template <typename K, typename V> void clear1( std::map<K, V*> *myMap)
{
if(myMap == NULL) return;
typename std::map<K, V*>::iterator itr = myMap->begin();
while (itr != myMap->end()) {
typename std::map<K, V*>::iterator toErase = itr;
++itr;
myMap->erase(toErase);
delete(toErase->second);
}
}
template <typename M> void clear2( M *myMap )
{
if(myMap == NULL) return;
for ( typename M::iterator it = myMap->begin(); it != myMap->end(); ++it ) {
delete it->second;
}
myMap->clear();
}
class MY_CLASS
{
public:
int counter;
string *message;
MY_CLASS(int c, string *m):counter(c), message(m) {
std::cout << "Constructor MY_CLASS " << this << std::endl;
};
~MY_CLASS()
{
if(message) {
cout << "Being destroyed MY_CLASS: " << *message << " this = " << this <<endl;
}
else {
cout << "Being destoyed MY_CLASS: " << " this = " << this <<endl;
}
if(message) {
delete message;
message = NULL;
}
}
MY_CLASS(const MY_CLASS & other)
{
std::cout << "Copy Constructor MY_CLASS " << this << std::endl;
//1.
counter = other.counter;
//2.
if(other.message) {
message = new string;
*message = *other.message; // copy the value
}
else {
message = NULL;
}
}
};
void print(const string *str,MY_CLASS *& value, void *)
{
if (value && value->message)
cout << value->counter << " ! " << *(value->message) << endl;
}
int main() {
std::map<std::string, MY_CLASS *> *mpa = new std::map<std::string, MY_CLASS *>;
MY_CLASS *p = new MY_CLASS(2, new string("abc"));
mpa->insert(std::pair<std::string, MY_CLASS *>("1", p));
mpa->insert(std::pair<std::string, MY_CLASS *>("2", p));
clearAndDestroy(mpa);
delete mpa;
return 0;
}
Output:
Constructor MY_CLASS 0x111ccb0
Being destroyed MY_CLASS: abc this = 0x111ccb0
Being restricted to C++98 is clearAndDestroy my best option? Thank you!
Another approach you can take is using an object wrapper. Place the pointer you want within an object and have the destructor call the delete on the pointer. Basically building a simple "smart-pointer".
class AutoDeletePtr {
MY_CLASS* pointer;
AutoDeletePtr(MY_CLASS* myObjectPtr) {pointer = myObjectPtr};
~AutoDeletePtr() {delete(pointer)};
}
You can insert these objects into the std::map.

How to notify ListView that DataModel has changed

I created a ListView and I want to use it with a custom DataModel. However, I have a problem: at the moment the view gets created, I don't have the data loaded into the model. The model data is set after the view is created and when I set the data onto the model, the view doesn't update and doesn't read again the model data. This is my ListView:
ListViewCountainer.qml
Container {
// countryModelData is set after ListViewCountainer gets created
// when countryModelData gets set, the model is populated with data
property variant countryModelData
leftPadding: 20.0
rightPadding: 20.0
topPadding: 20.0
bottomPadding: 20.0
CountryDetailsListView {
id: countryDetailsListView
dataModel: CountryDataModel {
countryData: countryModelData
}
}
}
And here is my model:
countrydatamodel.h
#ifndef COUNTRYDATAMODEL_H_
#define COUNTRYDATAMODEL_H_
#include <QtCore/QAbstractListModel>
#include <QtCore/QList>
#include <QObject>
#include <QtCore/QVariant>
#include <bb/cascades/DataModel>
#include <bb/data/JsonDataAccess>
class CountryDataModel : public bb::cascades::DataModel
{
Q_OBJECT
Q_PROPERTY(QVariant countryData READ getCountryData WRITE setCountryData)
public:
CountryDataModel(QObject* parent = 0);
virtual ~CountryDataModel();
Q_INVOKABLE int childCount(const QVariantList& indexPath);
Q_INVOKABLE QVariant data(const QVariantList& indexPath);
Q_INVOKABLE bool hasChildren(const QVariantList& indexPath);
Q_INVOKABLE QString itemType(const QVariantList& indexPath);
Q_INVOKABLE void removeItem(const QVariantList& indexPath);
Q_INVOKABLE QVariant getCountryData();
Q_INVOKABLE void setCountryData(QVariant data);
private:
QVariantList m_elements;
};
#endif /* COUNTRYDATAMODEL_H_ */
countrydatamodel.cpp
#include <src/countrydatamodel.h>
#include <QtCore/QtAlgorithms>
#include <QtCore/QDebug>
#include <bb/cascades/DataModel>
#include <bb/data/JsonDataAccess>
CountryDataModel::CountryDataModel(QObject* parent) : bb::cascades::DataModel(parent)
{
}
CountryDataModel::~CountryDataModel()
{
}
bool CountryDataModel::hasChildren(const QVariantList &indexPath)
{
qDebug() << "==== CountryDataModel::hasChildren" << indexPath;
if ((indexPath.size() == 0))
{
return true;
}
else
{
return false;
}
}
int CountryDataModel::childCount(const QVariantList &indexPath)
{
qDebug() << "==== CountryDataModel::childCount" << indexPath;
if (indexPath.size() == 0)
{
qDebug() << "CountryDataModel::childCount" << m_elements.size();
return m_elements.size();
}
qDebug() << "==== CountryDataModel::childCount" << 0;
return 0;
}
QVariant CountryDataModel::data(const QVariantList &indexPath)
{
qDebug() << "==== CountryDataModel::data" << indexPath;
if (indexPath.size() == 1) {
return m_elements.at(indexPath.at(0).toInt());
}
QVariant v;
return v;
}
QString CountryDataModel::itemType(const QVariantList &indexPath)
{
Q_UNUSED(indexPath);
return "";
}
void CountryDataModel::removeItem(const QVariantList& indexPath)
{
if(indexPath.size() == 1) {
m_elements.removeAt(indexPath.at(0).toInt());
}
emit itemRemoved(indexPath);
}
QVariant CountryDataModel::getCountryData()
{
return QVariant(m_elements);
}
void CountryDataModel::setCountryData(QVariant data)
{
m_elements = data.toList();
qDebug() << "================== CountryDataModel: " << m_elements;
}
I put some debug messages in the childCount function for example and it gets called only once, which means that the ListView asks the model for the data just once, when the model is created.
Is it possible to force ListView to read again the data from the model after the model gets populated with data? Or how could I make this approach work and load the data in the view?
Thanks!
In order for the model to be updated, the setCountryData member function needs to be updated like so:
void CountryDataModel::setCountryData(QVariant data)
{
m_elements = data.toList();
emit itemsChanged(bb::cascades::DataModelChangeType::AddRemove, QSharedPointer< bb::cascades::DataModel::IndexMapper >(0));
}
FML...
You need to declare a signal for the property you want to update in backend.
Q_PROPERTY(QVariant countryData READ getCountryData WRITE setCountryData NOTIFY contryDataChanged)
add its declaration as well.
Then you say -
emit contryDataChanged();
wherever you feel like list should re-read contents. (normally setter methods).

Why do I need to refer an object of an inherited class through a pointer to its base class?

Why do I need to refer an object of an inherited class through a pointer to its base class, when I am aware that the call to a function, exclusive to the inherited class, will produce a compilation time error?
Why Polymorphism?
Edit:
Here's a small piece of code as an example:
enum Suit { Spade, Heart, Club, Diamond };
enum Val { Ace=1, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King };
class Card {
private:
Val val;
Suit suit;
public:
Card(Val val, Suit suit) : val(val), suit(suit) {
cout << "Card constructor called" << endl;
}
int get_val() { return val; }
Suit get_suit() { return suit; }
};
class BlackJackCard : public Card {
public:
int garbage;
BlackJackCard(Val val, Suit suit) : Card(val, suit), garbage(9) {}
int get_val() {
Val tmpVal = (Val)Card::get_val();
if(tmpVal == 1) return 11;
if(tmpVal < 10) return tmpVal;
return 10;
}
int exclusive_to_BJC() {
cout << "I do nothing!! and the garbage value my object holds is " << garbage << endl;
}
};
int main() {
Card *newCard = new BlackJackCard(King,Spade);
cout << newCard->get_val() << endl; // 13
cout << newCard->get_suit() << endl; // 0
/*Why should I use a base class referencing if I can't access all the*/
/*members of the object I have constructed(except for the virtual functions).*/
// cout << newCard->exclusive_to_BJC() << endl;
// cout << newCard->garbage << endl;
BlackJackCard *new_bjCard = new BlackJackCard(King,Spade);
cout << new_bjCard->get_val() << endl; // 10
cout << new_bjCard->get_suit() << endl; // 0
cout << new_bjCard->exclusive_to_BJC() << endl;
}
Mainly for that reason (follow the link): low coupling.
If you talk about pointers, I understand C++, so you can take look at this explained example too.
You don't need to, you can. In fact, the vast majority of the time, it is better to take advantage of this possibility, to obtain better code. Consider:
class Vehicle
{
};
class Car : public Vehicle
{
};
int f(Vehicle *)
{
// code written here will be able to work on any type of vehicle.
}
OOP allows you to write f() in way that all vehicles are treated the same way, from the point of view of f(). In fact, a Car can have specialized functionality for Vehicle's function, without f() even needing to know.

Best way of structuring methods to handle derived types

I have an inheritance hierarchy similar to below and I want to write my DAL to persist these objects but am unsure as to the best way of structuring it?
Pet <- Dog <- Alsation and Labrador
Pet <- Cat <- Persian and Tabby
Although all classes inherit from Pet, each method will need to call a different stored procedure and add different sql parameters. There will be some common parameters though.
A few ideas:
(1) PetDal with overloaded save method that takes in each derived type.
(2) PetDal with separate SaveLabrador, SaveTabby methods.
(3) Base PetDal plus inherited LabradorDal, TabbyDal classes, one per dervied type with a common interface. eg void Save(Pet pet) which would need to cast the pet to the derived type within each method (strategy method).
(4) Some other way.
(1) and (2) are really the same, just syntactically different. One problem with (4) is that if you want to deal with different persistent types (flat files, databases etc) then you will have to have a class for each permutation (AlsationToFileDAL, AlsationToSybaseDAL, etc).
You could use (1)/(2) with double dispatch, e.g.:
// pets.h
#include <string>
#include <iostream>
class Alsation;
class Persian;
class PetDAL
{
public:
virtual ~PetDAL () {}
virtual void save (const Alsation* alsation) = 0;
virtual void save (const Persian* persian) = 0;
};
class Pet
{
std::string name_;
public:
Pet (const std::string& name) : name_ (name)
{}
virtual ~Pet () {}
std::string getName () const
{
return name_;
}
virtual void save (PetDAL* dal) const = 0;
};
class Dog : public Pet
{
bool sleepWalks_;
public:
Dog (const std::string& name, bool sleepWalks) : Pet (name), sleepWalks_ (sleepWalks)
{}
bool getSleepWalks () const {return sleepWalks_;}
};
class Alsation : public Dog
{
public:
Alsation (const std::string& name, bool sleepWalks) : Dog (name, sleepWalks)
{}
virtual void save (PetDAL* dal) const
{
dal->save (this);
}
};
class Cat : public Pet
{
int purrsPerMinute_;
public:
Cat (const std::string& name, int purrsPerMinute) : Pet (name), purrsPerMinute_ (purrsPerMinute)
{}
int getPurrsPerMinute () const {return purrsPerMinute_;}
};
class Persian : public Cat
{
public:
Persian (const std::string& name, int purrsPerMinute) : Cat (name, purrsPerMinute)
{}
virtual void save (PetDAL* dal) const
{
dal->save (this);
}
};
class PetDALCoutImpl : public PetDAL
{
public:
virtual void save (const Alsation* alsation)
{
std::cout << "Saving alsation " << std::endl
<< "\tname=" << alsation->getName () << std::endl
<< "\tsleepwalks=" << alsation->getSleepWalks () << std::endl;
}
virtual void save (const Persian* persian)
{
std::cout << "Saving persian " << std::endl
<< "\tname=" << persian->getName () << std::endl
<< "\tpurrsPerMinute=" << persian->getPurrsPerMinute () << std::endl;
}
};
int test (int argc, char* argv[])
{
Dog* dog = new Alsation ("fido", true);
Cat* cat = new Persian ("dave", 10);
PetDAL* petDAL = new PetDALCoutImpl ();
dog->save (petDAL);
cat->save (petDAL);
delete cat;
delete dog;
return 0;
};
I.e. the Pet base class knows its subclasses can be saved to a DAL, but it has no dependency on the DAL implementations.
Have you thought about using a pattern like the strategy pattern? It might fit your needs as you can have different strategies for different implementations, whilst still using properties/methods from the abstract class?