Skip navigation.

Beyond the Sky

The place where surface stop and share the experience of life

Posts tagged with "cpp"

pure virtual function

,

What is the different between pure virtual function and virtual function?

Virtual function is used to ease polymorphism implementation, which allows the c++ compiler to differentiate the actual "type" of the objects created which derived from a base class.

Pure virtual function is also virtual function, but it do not have a body. It looks just like a function declaration, and it forced the derived class to implement the function defination. (compiler gives error if the derived class do not define the pure virtual function). The base class that contains pure virtual function is call abstract class. It defines generic interfaces without specified the functionalities.

How to declare virtual function and pure virtual function?
That is simple, just add the magic keyword infront of the function you wanna turn it to virtual function:
class CPolygon {
  protected:
    int width, height;
  public:
    void set_values (int a, int b)
      { width=a; height=b; }
    virtual int area () //THIS MAKES THE FUNCTION VIRTUAL
      { return (0); }
  };

How about Pure Virtual Function?
class CPolygon {
  protected:
    int width, height;
  public:
    void set_values (int a, int b)
      { width=a; height=b; }
    virtual int area ()=0; //PURE, NO INLINE DEFINATION
  };

I remember when I first learn about pure virtual function, it was 6 years ago. Never used and exam also didn't covers. Its been awhile I didn't really touch Object-Oriented C++.

c++ constant pointer

,

To declare a const pointer point to an array, look at the four lines

1 int const* q = new int[50];
2 int* const q = new int[50];
3 const int* q = new int[50];
4 const* int q = new int[50];


Do they means the same? Not all are the same. Line 4 is invalid declaration, line 1 and 3 are identical.
For line 1 and 3, the value in the array are constant, you can move your pointer like q++ but you cannot change the value like *q=8 or q[0]=8
For line 2, the pointer is constant, that means you may change the value but you may not move your pointer like q++.

It can be very confusing, thats why i blog it for future reference.

Memory leak example

,

//: C13:BadVoidPointerDeletion.cpp
//// Deleting void pointers can cause memory leaks
#include <iostream>
using namespace std;
class Object {
   void* data; // Some storage
   const int size;
   const char id;
   public:
   Object(int sz, char c) : size(sz), id(c) {
   data = new char[size];
   cout << "Constructing object " << id
        << ", size = " << size << endl;
             }
   ~Object() {
   cout << "Destructing object " << id << endl;
   delete []data; // OK, just releases storage,
                  // no destructor calls are necessary
             }        };

int main() {
         Object* a = new Object(40, 'a');
         delete a;
         void* b = new Object(40, 'b');  
         delete b; //delete b without calling constructor will cause the data[] unreleased 
                   //and leads to memory leak.
           } ///:~ picked from pg 584 of thinking in c++ by bruce


When you compile this code, it do have warning:
$ g++ -o memleak{,.cc}
memleak.cc: In destructor 'Object::~Object()':
memleak.cc:17: warning: deleting 'void*' is undefined
memleak.cc: In function 'int main()':
memleak.cc:26: warning: deleting 'void*' is undefined

If you run it, you get the output:
Constructing object a, size = 40
Destructing object a
Constructing object b, size = 40

Destructor of object b is not called, it causes memory leak.

Singleton Class

,

//: C10:Singleton.cpp
// Static member of same type, ensures that
// only one object of this type exists.
// Also referred to as the "singleton" pattern.
#include <iostream>
using namespace std;
class Egg {
static Egg e;
int i;
Egg(int ii) : i(ii) {}
Egg(const Egg&); // Prevent copy-construction
public:
static Egg* instance() { return &e; }
int val() const { return i; }
};
Egg Egg::e(47);
int main() {
//! Egg x(1); // Error -- can't create an Egg
// You can access the single instance:
cout << Egg::instance()->val() << endl;
} ///:~

pick from thinking in c++ by Bruce Eckel, pg 454

This is an example code that a class where only a single object can be create.

const in class

,

When you want to create a constant in class which every object initialized from the class has its own different const value. That means the value must be initialized when instanciate and it do not allow to change for the rest of the time. This is the first time I read about this.

//: C08:ConstInitialization.cpp
// Initializing const in classes
#include <iostream>
using namespace std;
class Fred {
const int size;
public:
Fred(int sz);
void print();
};
Fred::Fred(int sz) : size(sz) {} // THE IMPORTANT PART
void Fred::print() { cout << size << endl; }
int main() {
Fred a(1), b(2), c(3);
a.print(), b.print(), c.print();
} ///:~

Object oriented programming in C++

,

On the halfway of reading "Thinking in C++ by Bruce Eckel", I just realized that, Object Oriented Programming in C++ can be written without using "class".

//: C05:Class.cpp
// Similarity of struct and class
struct A {
private:
int i, j, k;
public:
int f();
void g();
};
int A::f() {
return i + j + k;
}
void A::g() {
i = j = k = 0;
}
// Identical results are produced with:
class B {
int i, j, k;
public:
int f();
void g();
};
int B::f() {
return i + j + k;
}
void B::g() {
i = j = k = 0;
}
int main() {
A a;
B b;
a.f(); a.g();
b.f(); b.g();
} ///:~

The source code picked from the book page 290 shows that struct A and class B are the same. Object can be defined in struct exacally the same way as class, except that class defaults to private, whereas struct defaults to public.

C++ makes wonder

,

I discover something awkful while I read c++ source code of ns2.
Here is something i sort out for example

#include<iostream>
using namespace std;

class setup{
        private:
                int h;
        public:
                inline setup(){h=0;}
                inline int& seth(){ return h;}//here is the wonder
                inline void print(){ cout<<h<<endl;}
};

int main()
{
        setup s;
        s.print();
        s.seth()=5;//how could it happen?
        s.print();
        return 0;
}


When I look at the line similar like "s.seth()=5", i confused, I never see these kind of code before. But it works and it make sense. The inline function seth() in the class is actually return the memory address of "h", by storing value to a variable memory address, it make sense and it works.

Pascal Triangle Challenge

,

I remember last time, when i was learning how to code in C/C++, my Sifu ask me to do something challenging. Create something like pascal triangle:
        1
       121
      12321
     1234321
    123454321
   12345654321
  1234567654321
 123456787654321
12345678987654321

With only using TWO for loop and TWO variable. Yesterday I discover that i do backup my code, so i modified the code to suit gcc, here is the code.

#include<stdio.h>
#include<stdlib.h>

void piramid(int c)
{
        int x,y;
        for(y=0;y<c;y++)
        {
                for(x=0;x<c-(1+y)+((y*2)+1);x++)
                {
                        if(x<(c-(y+1)))printf(" ");
                        else
                        {
                                if(x-(c-(y+2))>y+1) printf("%d",(2*y)+2-(x-(c-(y+2)) ));
                                else printf("%d",(x-(c-(y+1))+1 ));
                        }
                }
                printf("\n");
        }
}

int main(int argc, char* argv[])
{
        if (argc==2)
        {

                if (atoi(argv[1])>9 || atoi(argv[1])<=1)
                        {
                                printf("Insert range within 2 to 9, ig. %s 9\n",argv[0]);
                                return 1;
                        }
                piramid(atoi(argv[1]));
        }
        else
                printf("Insert range within 2 to 9, ig. %s 9\n",argv[0]);
        return 0;
}




I do make my function recursive, so it uses only ONE for loop and ONE variable, but i lost that code.
December 2009
S M T W T F S
November 2009January 2010
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31