grumpier 149 Posting Whiz in Training

You're developing a realtime application, and don't know how to add values to elements of an array?????

Pull my other leg: it'll play a tune for you.

What is the criterion by which you would describe a method as "best"? If you are truly designing a realtime application, you will realise the significance of that question.

Salem commented: Jingle bells, jingle bells, jingle all the way? +26
grumpier 149 Posting Whiz in Training

To give you a clue about what's happening, 100! is about 9.3 by 10^157. To represent that, a 525 bit integer is needed (and that increases 530 bits to represent 101!). 64 bit is nowhere near enough: an unsigned 64 bit integer can only represent a maximum value of about 18446744073709551615 (approx 1.8 by 10^19).

Salem commented: Good analysis of the underlying problem that the numbers are huge +26
grumpier 149 Posting Whiz in Training

And you can use an executable compressor like nPack, see the attachment.

You need to be careful with executable compression. Compressed executables have some characteristics associated with self-modifying code (the decompression stub unpacks code and data into memory). Because of this, they can trigger false positives from anti-virus and anti-malware scanners. Also, to make it worse, a few products out there have actually carried virus or trojan horse payloads.

They can also make some programs run very inefficiently on operating systems that work with virtual memory (eg windows, unix). On those systems, executable compression is not a good idea if multiple instances of an executable are likely to be run concurrently.

If you accept these limitations, one that I've found rather useful is UPX.

StuXYZ commented: Thanks for comment about UPX +2
grumpier 149 Posting Whiz in Training

If by ``"c" programme'' you mean something that is compliant with one or both of the C standards, then there's only one answer: it's impossible. Your not wanting such an answer does not make it less true or correct.

If you wave a magic wand and decree that standard compliance doesn't matter, then the correct answer is whatever you (or anyone else) might define it to be. Microsoft have done this by introducing the WinMain() entry point which, for win32 applications, replaces the main() function. But that solution is specific to Microsoft operating systems and relies on specific compiler extensions that are outside the scope of the C standards.

grumpier 149 Posting Whiz in Training

You need to understand the difference between registering a callback function and actually calling it.

Setting TButton's OnClick event egisters a function that will be called when the user - eventually - presses the button. It does not call the function directly.

If, when the user presses the button, you want a particular function called, then call your function within the callback function (eg in the body of OnClick1). If you register the callback (eg TestBtn->OnClick = OnClick1;), then OnClick1 callback will be called whenever a user presses TestBtn. If OnClick1 calls myfunction(parameter) ......

grumpier 149 Posting Whiz in Training

Does it matter where you do this (int number::num) because I tried it out in the main and it works now but why? It doesn't seem to do anything other than maybe introduce it into a new block however you put it in the header and it still works. So what does it really do ?

It doesn't matter where you do it, as long as you obey the one-definition rule (ODR). Typical projects link together object multiple object files to create an executable, and each object file is created from a single source file. If you have two or more source files in your project, then only one of them can define number::num.

Placing the definition in your header file will violate the ODR if more than one source file in your project #include's it.

grumpier 149 Posting Whiz in Training

TButton's constructor needs to be passed a pointer to a TComponent (eg a parent form) that is responsible for managing the button.

It is also necessary to set various attributes: position, caption, visibility, the function to be called when the newly created button is created, etc etc. TButton is derived from TWinControl, so some inherited attributes probably also need to be set.

It would probably be easier to create a button on your form at design time, and have your function make that button visible as needed.

grumpier 149 Posting Whiz in Training

The only way in which a constructor can report an error is by throwing an exception.

The C++ standard has this to say (in Section 15.2 "Constructors and destructors" which is within Section 15 "Exception Handling"). [Note: I have not preserved font changes or emphasis in the quote]

1 As control passes from a throw-expression to a handler, destructors are invoked for all automatic objects constructed since the try block was entered. The automatic objects are destroyed in the reverse order of the completion of their construction.

2 An object that is partially constructed or partially destroyed will have destructors executed for all of its fully constructed subobjects, that is, for subobjects for which the constructor has completed execution and the destructor has not yet begun execution. Should a constructor for an element of an automatic array throw an exception, only the constructed elements of that array will be destroyed. If the object or array was allocated in a new-expression and the new-expression does not contain a new-placement, the deallocation function (3.7.3.2, 12.5) is called to free the storage occupied by the object; the deallocation function is chosen as specified in 5.3.4. If the object or array was allocated in a new- expression and the new-expression contains a new-placement, the storage occupied by the object is deallocated only if an appropriate placement operator delete is found, as specified in 5.3.4.

3 The process of calling destructors for automatic objects constructed on the path from a try …

rkumaram commented: good +1
grumpier 149 Posting Whiz in Training

When you mark a method of your class as virtual you give the user of your class the possibility to override that method. If you don't, the metod can't be overridden.

That statement is inaccurate on so many levels that I'm speechless. Non-virtual functions can also be overridden, but the behaviour differs from overridden virtual functions due to "name hiding", as described in the C++ standard.

The point of virtual member functions is that they allow functionality to be specified in a base class, and specialised in a derived class. For example, a generic Shape class might declare a virtual function named Area() to compute it's area, and another virtual function called Name(). Derived classes (which represent particular shapes) override those virtual function to give appropriate results for particular shapes.

class Shape
{
     public:
          Shape();
          virtual double Area() const = 0;
          virtual std::string Name() const = 0;
};

class Triangle: public Shape
{
     public:
          Triangle(double h, double w) : height(h), width(w) {};
          double Area() const {return 0.5*height*width;};

          std::string Name() const {return "Triangle";}

     private:
          double height, width;
};

class Circle : public Shape
{
     public:
         Circle(double r): radius(r) {};
         virtual double Area() const {return 4.0*atan(1.0)*radius*radius;};
          virtual std::string Name() const {return "Circle";}
      private:
            double radius;
};

Now, let's say we have a function that only knows about the Shape class, and wishes to print its name and area. For example;

void PrintArea(const Shape &s)
{
    std::cout << s.Name() << " - Area = " << s.Area() << '\n';
}
ddanbe commented: you made a point +3
Manutebecker commented: Excellent Post +1
grumpier 149 Posting Whiz in Training

What's dogmatic about the fact that globals are to be avoided at all cost?

Dogma (n) : A firmly held belief based on faith, and often stated as fact.

ddanbe commented: In my language they say : Get den diksten! +1
grumpier 149 Posting Whiz in Training

If there are common things that all classes which handle triangles have to do, put those functions into their own class (eg TriangleModelFile derived from ModelFile). Derive the specific/multiple classes (eg SpecificTriangleModelFile) from that generic triangle-handling class, and give it specific behaviour it requires.

It's often a good idea to make base classes are abstract (i.e. you can't instantiate them) and derived classes are concrete (i.e. they can be instantiated). That way you reduce the temptation to move things to a base class that are only needed by some derived classes.

Alex Edwards commented: Great advice =) +4
grumpier 149 Posting Whiz in Training

Don't know if it helps. I myself am not sure if it's ok to write it, but compiler doesn't complain:

void func(int n){
    int a[n];
    for (int i = 1; i <= n; i++) a[i+1] = i*i;
    for (int i = 1; i <= n; i++) std::cout<<a[i+1]<<std::endl;
    return;
}

The array declaration int a[n]; is not valid C++. Your compiler doesn't complain because it supports this as an extension. (Your compiler might also support the 1999 C standard (where such things are valid)).

To answer the original question, though, it depends on what you mean by "not using new key (without malloc too)". If you mean that your code does not invoke operator new or call malloc() directly, then you can use a standard container (std::vector, std::list, etc).

However, those containers work by performing dynamic memory allocation behind the scenes ... which means that code you write may not employ operator new or malloc(), but the containers themselves might.

Salem commented: Good catch. +23
grumpier 149 Posting Whiz in Training

So, my query is, why this is happening only in case of strings and not for the others( like int, float, single character)?

Because the %s format specifier tells printf() and related function that the corresponding argument is a pointer to char and to keep printing chars until it finds a zero.

When an array is passed to a function (be it array of char, double, or structs) only a pointer to the first element is passed. No information about the number of elements in the array is passed. So the function has to use some convention (as printf() does with the %s specifier) or make an assumption (eg it assumes the array is of length 5).

grumpier 149 Posting Whiz in Training

Start with T(0) = 1.

In a loop use the fact that T(n+1) = x*T(n)/(n+1) to compute each term. Add the terms together.

ohnomis commented: HE IS THE SOLVER OF e^x! GENIUS! +1
grumpier 149 Posting Whiz in Training

I have no idea how your teacher's program works -- you would have to post it. I can only suspect he used one of the huge integer libraries like I previously suggested. Its also possible he used strings instead of integers to avoid the limitations of integers.

Oh, please! Huge integer libraries or strings are needed for some things, but falling back on them for basic problems like this is crazy.

The program can go to much higher terms simply using the fact that e^x = 1 + x/1! + x^2/2! + ... and that the n-th term inthis is T(n) = x^n/n! It is trivial to show that T(n+1) = x*T(n)/(n+1).

The code to use this relationship to compute an approximation of e^x is easy. This avoids the possibility of overflow that is inherent in computing x^n or n! separately.

Salem commented: Good answer. +22
grumpier 149 Posting Whiz in Training

In addition, operator= sceleton should be:

ThreeD& operator=(const ThreeD& op2)
{
    if (this != &op2)
    {
         ....
    }
    return *this;
}

The above is common practice, but it is easily broken. Imagine, for example, a class that supports its own operator&() - it will not perform as you intend.

Generally, it is better to code in a manner that prevents self-assignment in the first place.

The most useful way I've found to do an assignment operator is;

void ThreeD::swap(ThreeD &op1, ThreeD &op2) 
{
     // do the swap in a way that is guaranteed not to throw exceptions
}

ThreeD& operator=(const ThreeD& op2)
{
    ThreeD temp(op2);
    swap(*this, temp);
    return *this;
}

This approach is exception safe (if an exception is thrown - a normal way of reporting a terminal error) the objects being acted on have no effect. No need to check for self-assignment: the only cost is associated with creating a temporary copy of *this.

This approach is recommended - as one of many practices to be used collectively - in some coding standards designed for using C++ in high criticality systems ie systems that will cause major real-world damage (eg people dying) if they behave incorrectly.

A fair amount of individuals stated that returning a reference of the actual object that represents the class is more preferable than returning a copy that has the reflected changes made on the object.

Yes it is.

Sure, for performance reasons, it might be better. But now you …

vijayan121 commented: ! +9
grumpier 149 Posting Whiz in Training

1) First, represent a polynomial (of the form c_0 + c_1*x + c_2*x^2 + .... c_n*x^n) is represented by an array with elements (c_0, c_1, c_2, c_3, .... c_n).

2) Work out how to multiply two arbitrary polynomials together. ie. given a polynomial A (a_0, a_1, a_2, a_3, .... a_n) and a polynomial B (b_0, b_1, b_2, b_3, .... b_m) work out how to obtain a polynomial A*B = C = (c_0, c_1, c_2, c_3, .... c_(m+n)). Hint: The process to produce C from A and B is called convolution.

3) For the first root on the command line, create a polynomial X = (root, 1).

4) For all other roots on the command line;
a) create a polynomial Y = (root, 1)
b) obtain a polynomial Z = X*Y using the approach worked out in Step 2.
c) set X = Z

5) Voila!!!

Salem commented: Make it count rep added. +21
grumpier 149 Posting Whiz in Training

Not even close.

You have declared myclass's length() method as taking one argument, and yourlen() calls it with two arguments.

Similarly, yourlen() is declared with no arguments, but when you call it you pass two to it. (I'll ignore the typo of calling a.youlen() rather than a.yourlen()).

If you declare a function taking n arguments, you have to pass exactly n arguments to it.

If you had tried to compile your code, your compiler would have complained bitterly.

grumpier 149 Posting Whiz in Training

Firstly, your variables a, b, and c are uninitialised: their value before entering the loop could be anything.

As to your loop, it doesn't really make sense.

You only need two variables. An index, that gets a value of 1 first time through the loop, 2 the second time, 3 the third time, etc. And a sum, which initially has a value of zero, and each time through the loop has the value of index added to it.

Try using descriptive variable names, and get rid of the "#define p printf" line. If you want to use printf, then type its name in full. Brevity is all well and good, but you've gone too far and have code which is not that easy for a mere mortal to understand, and therefore difficult to get right. You're lucky the code is small.

Oh: learn how to use code tags, so you code is laid out in a readable manner in your posts.

Nick Evan commented: All excellent tips +9
grumpier 149 Posting Whiz in Training

You're asking the wrong question. The compiler will attempt to invoke a copy constructor (assuming one exists) upon any attempt to create a copy of an object.

The real practical concern is whether you need to write the copy constructor yourself or let the compiler do it for you.

If you don't supply a copy constructor, the compiler will generate one by default. The compiler generated default invokes copy constructors of any base classes (in defined order) and then does a memberwise copy of any members of the class.

The general rule is that, if the compiler-generated default differs from the behaviour you need (eg managing a global resource) then you need to roll your own copy constructor.

The most common case is when a class contains a pointer, and the class uses dynamic memory allocation. The default-generated copy constructor copies the value of the pointer, so that two objects end up containing a pointer to the same thing. That makes things problematical for the destructor: when both objects are destroyed, the pointer is released twice, causing undefined behaviour. So you need to implement a copy constructor in this case to do a "deep copy".

One other rule of thumb is that any class that requires the programmer to write a copy constructor also requires the programmer to write an assignment operator.