#include <iostream>
#include <vector>
#include <string>
#include <deque>
using namespace std;
class OpenFile {
public:
OpenFile(string filename) {cout<<"Open a file\n"<<filename ; }
void destroyMe() { delete this; }
private:
~OpenFile() {cout<<"Destroy a
file in deconstructor\n" ; }
};
//--------------------------------------------------------------------
class BigArray {
vector<int > v; //huge array
int accessCounter; //1st member
int* v2; //2nd member
public:
int getItem(int index) const {
//accessCounter++;
//because using const -> can not change private member of class
const_cast <BigArray*>(this)->accessCounter++;
return v[index]; }
//getItem did not change any value of v, just take a bit of index,
getItem should be const
void setv2Item(int index, int x) const { *(v2 + index) = x; }
//this func maintain bitwise const of BigArray class,
it does not change any member of class directly
};
//--------------------------------------------------------------------
//const
and Function
class Dog {
int age;
string name;
public:
Dog() { age = 3; name = "dummy"; } //constructor
//const
parameter
//void
setAge(const int& a) { age = a; }
//func
//void
setAge(int a) { age = a;} //overload
func
//const
return value
const string getName() { return name; }
//const
func
void printDogName() const { cout << name <<" const"<< endl; }
//does
not change any member valuable of class
void printDogName() {
cout <<
getName() <<" non-const"<< endl; }
//does
not change any value of member of class
};
class Dog_ {
public:
~Dog_() { cout << "Dog destroyed\n"; }
void bark(){}
};
class YellowDog : public Dog_ {
public:
~YellowDog() { cout << "YellowDog destroyed\n"; }
};
class DogFactory{
public:
static Dog_* createYellowDog() { return (new YellowDog());}
};
int main() {
OpenFile* f = new OpenFile(string("hello world\n"));
f->destroyMe();
//-----------
Dog d;
d.printDogName();
const Dog d2;
d2.printDogName();
//-----------
Dog_* pd = DogFactory::createYellowDog();
delete pd;
return 0;
}
//-------------------------------
// 7/31
//Avoid
to call Virtual Function in Constructor or Destructor
class Cat {
public:
Cat() { cout << "Cat born." << endl; say(); }
virtual void say() { cout << "I am just a baby
cat!" << endl; }
void seeCat() { say(); }
~Cat() { say(); }
};
class Lion : public Cat{
public:
Lion() { cout << "Lion born." << endl; }
virtual void say() { cout << "I am just a yellow
lion." << endl; }
};
int main() {
Lion bucky;
bucky.seeCat();
//although
we call seeCat() of Cat class,
//say() func was called to
Lion class
}