Skip to content

I) Class

kalinosia edited this page Mar 13, 2021 · 1 revision

Class how to write

You can write yours in main, but better practice is to do this in other files. You can do two files for one class: one to declare class and functions (correctly class have attributes and methods!!) .h and second to definitite methods of class .cpp. This file you name the same like class for example class Animal have files: Animal.cpp and Animal.h. In file .h you can also give some definitions of methods. Exaple of that file:

class Dog
{
private:
    int age;
public:
    string name;
    Dog(){std::cout<<"Wow, nwe dog!"<<std::endl;} <- This is constructor with definition
    ~Dog(){std::cout<<"Bye dog!"<<std::endl;} <- Destructor with definition
    void giveDate(string name, int age); <- Function declaration
    void speak(){std::cout<<"Hau!!"<<std::endl;} <-Function with definition
};

Why you write public and private. Because class is private by default! When private you can use example in main...

Class_name.cpp

#include <iostream>
....
#include "Dog.h" //!!!!

using namespace std; //or not

void Dog::giveDate(string main_name, int age){
    name = main_name;
    this->age = age; //when date named the same you can use this
}

Struct vs Class

In Struct everything is public by default. In class is private.

Struct Dog{
    string name;
    void speak();
};

Create animal function

class Animal {
private:
	string name;

public:
	Animal() { cout << "Animal created. Constructor." << endl; }//not have that one when copy animal2
	Animal(const Animal& other) :name(other.name) {  cout << "Animal created by coping. Copy constr." << endl; }
	void setName(string name_set) { this->name = name_set;  };
	void speak() const { cout << "My name is: " << name << endl; }
	~Animal(){cout<<"Destructor"<<endl;}
};

Animal *createAnimal(){
    Animal *pAnimal = new Animal();
    pAnimal->setName("Bernis");
    return pAnimal;
    }

int main(){
    Animal *pDog = createAnimal();
    pDog->speak();
    delete pDog; //!!!
}

Create object and how to use; POINTERS, NEW, DELETE

    Animal *pCat = new Animal();
    //pCat.setName("Mark"); ERROR
    //*pCat.setName("Mark"); ERROR
    (*pCat).setName("Mark"); //Work but not pretty
    pCat->setName("Bob"); //That it's work! ###pointer->function###
    cout<<sizeof(pCat)<<endl; // always pointer = 8
    delete pCat; //ALWAYS delete if new !!! easy see because without this destructor not work

Table alocate memory (...) new & delete

Animal *pDogs = new Animal[10];
(...)
delete [] pDogs; //!!!
LIKE IN OTHER NEW MUST delete [] pointers; !!!!
char *pChars = new char[1000];
delete [] pChars;

Clone this wiki locally