Here is how I understood not just what virtual functions are, but why they're required:

Let's say you have these two classes:

class Animal { public: void eat() { std::cout << "I'm eating generic food."; } }; class Cat : public Animal { public: void eat() { std::cout << "I'm eating a rat."; } };

In your main function:

Animal *animal = new Animal; Cat *cat = new Cat; animal->eat(); // Outputs: "I'm eating generic food." cat->eat(); // Outputs: "I'm eating a rat."

So far so good, right? Animals eat generic food, cats eat rats, all without virtual.

Let's change it a little now so that eat() is called via an intermediate function (a trivial function just for this example):

// This can go at the top of the main.cpp file void func(Animal *xyz) { xyz->eat(); }

Now our main function is:

Animal *animal = new Animal; Cat *cat = new Cat; func(animal); // Outputs: "I'm eating generic food." func(cat); // Outputs: "I'm eating generic food."

Uh oh... we passed a Cat into func(), but it won't eat rats. Should you overload func() so it takes a Cat*? If you have to derive more animals from Animal they would all need their own func().

The solution is to make eat() from the Animal class a virtual function:

class Animal { public: virtual void eat() { std::cout << "I'm eating generic food."; } }; class Cat : public Animal { public: void eat() { std::cout << "I'm eating a rat."; } };

Main:

func(animal); // Outputs: "I'm eating generic food." func(cat); // Outputs: "I'm eating a rat."

Done.

https://stackoverflow.com/questions/2391679/why-do-we-need-virtual-functions-in-c

 

 

 

 

Why do we need virtual functions in C++?

I'm learning C++ and I'm just getting into virtual functions. From what I've read (in the book and online), virtual functions are functions in the base class that you can override in derived class...

stackoverflow.com

binding 과 관련된 일이다..필요하면 early binding/late binding 찾아봐

https://www.geeksforgeeks.org/virtual-function-cpp/

이런 코드를 봤는데

소스 코드

#include <iostream>

class Foo {
public:
  int bar;
  Foo(int num): bar(num) {};
};

int main(void) {
  std::cout << Foo(42).bar << std::endl;
  return 0;
}

여기서 : bar(num)처럼 쓰는건 뭔가요?

저렇게 쓰는 걸 처음 봤는데 다른 함수를 호출하는 건가요? 아니면 생성자에서 쓴걸 보면 생성자랑 관련 있는 건가요?


Foo(int num): bar(num) 은 초기화 리스트라고 하고, 멤버 변수 bar를 num으로 초기화하는 역할을 합니다.

//초기화 리스트
Foo(int num): bar(num) {};

//함수에서 초기화
Foo(int num)
{
   bar = num;
}

그냥 생성자 함수{} 내에서 초기화하는 것과, 이렇게 초기화 리스트를 쓰 는것의 차이는

초기화 리스트에서 초기화를 하는 경우, 생성자가 호출될 때 객체의 생성과 초기화가 한 번에 이루어집니다.

생성자 함수 내{}에서 초기화를 하는 경우, 객체가 생성되어, default생성자로 초기화된 상태에서 다시 한 번 할당받게 하게 됩니다. 이 경우엔 default할당-유저할당의 2단계를 거치게 돼서 오버헤드가 생깁니다.

초기화 리스트를 써야만 하는 상황은 크게 다음과 같습니다

  • 클래스가 레퍼런스를 멤버로 가질 때
  • non static const멤버가 있을 때
  • default 생성자가 없을 때
  • base class를 초기화할 때
  • 생성자 파라미터의 이름이 데이터 멤버랑 같을 때(이 경우는 this를 써서 해결할 수도 있습니다)

예를 들면

class MyClass
{
    public:
        int &i; //레퍼런스 멤버. 초기화 리스트를 써야 함
        int b;
        //Non static const 멤버. 초기화 리스트를 써야 함
        const int k;  

    //생성자 파라미터의 이름이 데이터 멤버랑 같음. 초기화 리스트를 쓸수 있음(선택 가능)
    MyClass(int a, int b, int c):i(a),b(b),k(c)
    {
        /*
        초기화 리스트를 쓰고 싶지 않은 경우
        this->a = a
        같이 써야 함
        */
    }
};

class MyClass2:public MyClass
{
    public:
        int p;
        int q;
        //base class인 MyClass가 default생성자가 없기 때문에 무조건 초기화 리스트에서 초기화해줘야 함
        MyClass2(int x,int y,int z,int l,int m):MyClass(x,y,z),p(l),q(m)
        {
        }

};

int main()
{
    int x = 10;
    int y = 20;
    int z = 30;
    MyClass obj(x,y,z);

    int l = 40;
    int m = 50;
    MyClass2 obj2(x,y,z,l,m);

    return 0;
}


서버


1. 서버

-Serv.h


-Serv.cpp

 

-main.cpp(Server)


2. 클라이언트


-main.cpp


mutex를 걸어주는 방법에는 critical section (함수?) 도 있다고 한다.....

EVENT 생성시 마지막 인자로 들어가는 TEXT는 안주는 것이 좋다.

EVENT TEXT가 같으면 다른 프로그램에서도 같은 EVENT로 인식을 하기 때문에


-thread 종료를 시키는 방법


thread들은 while문을 돌때 조건으로 flag check를 한다.

delete(소멸자에서) 할때 flag set을 한뒤 waitEvent

thread에서 set된 flag를 확인하고 while문을 빠져나온다.

while문을 빠져나와 thread를 빠져 나오기전 setEvent를 해주면 이벤트를 기다리던 delete함수가 메모리 해제를 시작한다.



'Programming Language > C++' 카테고리의 다른 글

Why do we need virtual functions in c++?  (0) 2019.04.05
생성자 뒤에 콜론(:)  (0) 2017.03.08
MultiThread Programming  (0) 2016.08.17

소켓통신: http://www.codeproject.com/Articles/11740/A-simple-UDP-time-server-and-client-for-beginners

mutex: https://msdn.microsoft.com/ko-kr/library/windows/desktop/ms686927(v=vs.85).aspx

callback함수: http://stackoverflow.com/questions/10555566/difference-between-c11-stdbind-and-boostbind

+ Recent posts