deceptikon 1,790 Code Sniper Team Colleague Featured Poster

deceptikon, your method compiled just fine but didn't actually change the output of the number. If I entered 12345 it would still out put 12345 rather than 012345 which is what I'M trying to get.

Let's make something abundantly clear: the type of string matters. Are you using a C++ string object? In that case, my solution works:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string s = "12345";

    s = '0' + s;

    cout << "'" << s << "'" << '\n';
}

If you're using a C-style string, which is nothing more than an array of char terminated by '\0', it's less intuitive, more awkward, and easier to get wrong:

#include <cstring>
#include <iostream>

using namespace std;

int main()
{
    char s[10] = "12345";

    // Shift everything to the right by 1 to make room at the front
    memmove(s + 1, s, strlen(s) + 1);

    // Prepend '0'
    s[0] = '0';

    cout << "'" << s << "'" << '\n';
}
tux4life commented: From all suggested approaches I like these the most. +13
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

yeah but i have very short time to submit it so i ask like that :)

Last I checked, that wasn't a viable excuse for cheating. Please read our rules. When posting homework questions, we require proof of effort before you'll be offered any help. So even though you're short on time, you've already wasted quite a bit by not following proper procedure on Daniweb.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

sizeof is meaningless for strings. At best you'll get the size of an array, which may or may not correspond to the length of a string contained within that array. At worst you'll get the size of a pointer or the size of the containing object (eg. std::string), neither of which are useful when you want the number of characters in the string.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

but isn't the last null that the temp points to is in the case the root->left?

It is, but in C++ all null pointers are the same. Once temp becomes null, you have no way of determining which node pointed to it. You can think of it like this (using a simple tree):

allroadsnull

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Why so many levels of indirection? The top two clearly aren't necessary within this program, so you could just do this:

int **p = new int*[rows];

for (int i = 0; i < rows; i++)
    p[i] = new int[columns];
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I think it was 30 years ago, before the first c++ standards.

C++ never supported void main() officially, even at the time of C with Classes. That was always a compiler extension, just as it is now.

I think the standard says that main() will return 0 automatically.

True for C, but not C++

C++ has supported an implicit return from main() since C++98, and C has supported it since C99.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

As I am completely a newbie in this I want to know where to start.

I'd start by figuring out how a website might be blocked, regardless of which browser makes the request.

Please provide me with any useful links which can help me.

This link is probably the only one you need.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

what is the id and pass.

They're hard coded:

11user1 = Pwd1
12user2 = Pwd2
13user3 = Pwd3

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

ya k tinstaafi i am the new one to dot net plat form , i dont know exactly what is what thats why i am asking again clearly

If you don't read the links, which have far more extensive information than a post here would contain, what makes you think that someone posting the code here will help any more?

Anyway, consider the following and see if it helps. It's basically the bare minimum for sending an email through SMTP:

using System;
using System.Net;
using System.Net.Mail;

public class Program
{
    public static void Main()
    {
        try
        {
            SendEmail(
                "smtp.live.com",          // Hotmail's SMTP server
                "foodiddles@hotmail.com", // Note: Bogus login information
                "imapassword",
                true,                     // SSL required for Hotmail
                "foodiddles@hotmail.com", // Bogus sender
                "foo@bar.com",            // Bogus recipient
                "Test Email",
                "This is a test email.");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }

    public static void SendEmail(
        string server, string userName, string password, bool useSSL, // Server info
        string sender, string recipient, string subject, string body, // Message info
        int timeout = 30)
    {
        using (var mail = new MailMessage())
        {
            var smtp = new SmtpClient(server);

            smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
            smtp.Credentials = new NetworkCredential(userName, password);
            smtp.EnableSsl = useSSL;
            smtp.Timeout = 1000 * timeout;

            mail.From = new MailAddress(sender);
            mail.To.Add(new MailAddress(recipient));
            mail.Subject = subject;
            mail.Body = body;

            smtp.Send(mail);
        }
    }
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The Legacy Languages forum doesn't have a specific language parser, so what you see is default coloration, and the quote operator is being parsed as a string rather than the Scheme quote operator. Obviously you can fix it by being explicit with (quote [...]) instead of '[...]. Unfortunately, introspectively looking at the code in a post to determine which parser to use is tricky at best.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What's musorv_uzi? If it's a variable then you probably intended to say $arr222[$musorv_uzi]. If it's a string, you need to quote it. Presumably it could be a constant as well, but it's clearly not defined in the current scope.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What's wrong here:

while(temp!=NULL){[...]}
temp=add;

If temp is NULL after the loop then it no longer refers to the tree in any way. So assigning add to temp will accomplish absolutely nothing when insert() returns.

This was actually a stumbling block for me when I first started learning referential data structures. A null pointer isn't a part of the structure, and as soon as you set your reference into the data structure to null, you're done with it. To insert a node where a null currently resides, you must have a reference to the previous node:

while (true) {
    if (temp->item >= add->item) {
        if (temp->left == NULL)
            break;

        temp = temp->left;
    }
    else {
        if (temp->right == NULL)
            break;

        temp = temp->right;
    }
}

if (temp->item >= add->item)
    temp->left = add;
else
    temp->right = add;

There are a number of ways to do it, of course, but the above highlights the fact that as soon as temp becomes null, you're screwed.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You're not really doing it at the same time. Think of the output as a sequence of rows, and each row as a sequence of characters where the blank space between items is literally whitespace. So for each 'x' in your example, print a space character.

The pseudocode for the algorithm is this:

# Print the header row
for i = 0 to 9
    print i
    print space
end

print newline

# Print subsequent rows
for i = 0 to 9
    # Print the first number at column 0
    print i

    # Match the column of the second number
    for j = 0 to 9
        print space
    end

    # Print the second number at the matching column
    print i
    print newline
end
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

If you're too lazy to figure out what project you want to do, the project will be stillborn because you're clearly too lazy to actually do the project.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Are you asking about mov in general, or are you asking specifically about moving the low order byte of a register?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

by alternatives i meant fix to this as im quite inexperienced in the area!

Clearly. You seem to understand what Armstrong numbers are, that's not a problem. But your C is atrocious to the point where I'd question if you know it at all. Because enumerating all of the problems in your code and explaining how to fix them would take herculean efforts, I'll recommend that you start over from the beginning of your textbook, and work through it more slowly to make sure that you're absorbing all of the information. Fundamentals are important because if you don't have a strong foundation, everything will be exponentially more difficult.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Have you tried:

s = '0' + s;

That's assuming you're using a std::string object. For C-style strings I'd recommend not using them because it makes just about everything harder.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

If it's not working, have you considered fixing it instead of asking for something completely different? Or is it that you stole that code from somewhere and aren't capable of fixing it?

I can tell you right now that (a[i])^3 is meaningless because ^ is a bitwise XOR operator, not a power operator.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

@deceptikon does strlen() function give the length of string in O(n) or O(1)?

You really can't assume that it's better than O(n), and it would take quite an idiotic programmer to make it worse than O(n). ;) The structure of C-style strings isn't conducive for optimizations that would improve the complexity because in the end you're searching for a character in the string. The library doesn't have control over when or where that character is placed, or even if it exists at all.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What's the exact error? I don't have Xcode handy.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Comparing floating point values for equality is also fraught with peril. You'd be better off converting them to strings and then doing the comparison. That way the not insignificant work of handling a precise representation of the value is deferred to the standard library. A "close enough" test is often acceptable as well:

#include <cmath>
#include <type_traits>

template <
    typename T, 
    typename = std::enable_if<std::is_floating_point<T>::value>::type>
inline bool approximate_eq(T x, T y, T percent_tolerance)
{
    return std::fabs(x - y) / x <= percent_tolerance;
}

#include <iostream>

void test_difference(double x, double y, double percent_tolerance)
{
    std::cout << x << " and " << y << " are "
              << (approximate_eq(x, y, percent_tolerance) ? "" : "NOT ")
              << "within " << percent_tolerance * 100 << "% of each other\n";
}

int main()
{
    test_difference(2.5, 2.3, .05);
    test_difference(2.5, 2.4, .05);
    test_difference(2.5, (1.0 * 2 + .5), .05);
    test_difference(2.5, 2.6, .05);
    test_difference(2.5, 2.7, .05);
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

@moschops i am trying to avoid that loop. thats why i am using memset which fails.

What do you think memset() does? Internally it's just a loop. There might be some unrolling involved or it might be written in assembly to speed things up, but it's still a loop.

Here is a conforming (and portable) implementation of memset(). You'll notice there's not much to it, and it matches the spirit of Moschops' example.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Didn't you write it? Why would you need someone to explain to you how your own code works?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

and change line 138 to use getchar().

That won't work because getchar() requires a newline to terminate input in the shell. getch() is used because it's a non-blocking input function. This is an appropriate usage of the conio library.

perhaps a while loop around lines 138-168

Yes. Basically you need a game loop that runs forever and handles any input appropriately. For example:

#include <iostream>
#include <Windows.h>

int main()
{
    CONSOLE_SCREEN_BUFFER_INFO info;
    conio::Keys dir = conio::Keys::RIGHT;
    POINT curr = {1, 1};

    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);

    for (;;) {
        // Clear the current position
        conio::gotoxy(curr.x, curr.y);
        conio::putch(' ');

        // Handle input if necessary
        if (conio::kbhit()) {
            int ch = conio::get_code();

            if (ch == conio::Keys::ESC)
                break;

            switch (ch) {
            case conio::Keys::UP:    dir = conio::Keys::UP;    break;
            case conio::Keys::DOWN:  dir = conio::Keys::DOWN;  break;
            case conio::Keys::LEFT:  dir = conio::Keys::LEFT;  break;
            case conio::Keys::RIGHT: dir = conio::Keys::RIGHT; break;
            }
        }

        // Always adjust the direction to keep things moving
        switch (dir) {
        case conio::Keys::UP:    curr.y = curr.y > 1 ? curr.y - 1 : curr.y;             break;
        case conio::Keys::DOWN:  curr.y = curr.y < info.dwSize.Y ? curr.y + 1 : curr.y; break;
        case conio::Keys::LEFT:  curr.x = curr.x > 1 ? curr.x - 1 : curr.x;             break;
        case conio::Keys::RIGHT: curr.x = curr.x < info.dwSize.X ? curr.x + 1 : curr.x; break;
        }

        // Move to the new position
        conio::gotoxy(curr.x, curr.y);
        conio::putch('@');

        Sleep(100);
    }
}

Note that I'm using a custom conio library for Win32 in that example rather than the conio.h that may or may not …

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

How can I calculate CLOCKS_PER_SEC.. It is defined as 1000 in ctime. I don't want it defined. I want to calculate the actual value..

CLOCKS_PER_SEC is a standard macro, you can ignore it if you'd like, but you shouldn't redefine it.

So what is CLOCKS_PER_SEC and why is it defined as 1000? How can I calculate it?

CLOCKS_PER_SEC is the number of units calculated by std::clock() over the span of one second. std::clock() is defined as such:

"The clock function returns the implementation’s best approximation to the processor
time used by the program since the beginning of an implementation-defined era related
only to the program invocation."

As a concrete example, one of my simple C standard libraries implements clock() as this:

/*
    @description:
        Determines the processor time used.
*/
clock_t clock(void)
{
    return _sys_getticks() - __clock_base;
}

Where __clock_base is a static object initialized to _sys_getticks() at program startup, and _sys_getticks() is defined like so:

/*
    @description:
        Retrieves the process' startup time in clock ticks.
*/
long long _sys_getticks(void)
{
    return GetTickCount64();
}

GetTickCount64() is a Win32 API function that returns the number of elapsed milliseconds since system startup, which means for this implementation clock() returns milliseconds since program startup, and CLOCKS_PER_SEC is the number of milliseconds in a second (ie. 1000).

I'm trying to run a function every actual tick.

Define "tick". Apparently the tick of std::clock() isn't sufficient, and neither is the …

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

hello,please tell us the algorithms for extracting text from image consisting of printed text.

Because OCR is just as simple as that...NOT!

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I suspect that semicolon at the end has something to do with it not doing what you want:

#include <iostream>

int main()
{
    int year = 1985;

    if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))
        std::cout << "Leap year\n";
    else
        std::cout << "Not a leap year\n";
}

I gave you a complete function, there was no need to change it. Especially since by changing it you apparently broke it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

On FF 18.0.1 (release version) / Windows 7, clearing the cache (Ctrl+F5) resulted in [...]

I'm assuming you meant clearing the cache followed by Ctrl+F5, because Ctrl+F5 by itself just does a hard reload of the page. Reloading the page, even a hard reload, won't do jack diddly. ;) To fully clear the cache you'd go into the advanced browser options and clear cached content from the options provided.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Can any 1 please help me with it?

What kind of help do you want? You clearly haven't done anything yourself, so it's hard to construe "help" to mean anything except "tell me the solution and how to code it".

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Anyways that Firefox bug is odd....

We've seen that one before, and clearing the cache was one of the fixes that corrected it. If you haven't already tried clearing the cache, please do so and see if it helps.

We use a lot of scripting on Daniweb, and occasionally it conflicts with the straight HTML stuff in funky ways when the scripts are out of date. That's why if there's a problem related to scripts, the first suggestion we'll make is to clear your cache.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Thinking about it, I'm unsure why anyone would give a student such a task, how could you ever have a c-style array you do not know the size of anyway?

I suspect one of two things:

  1. The OP simply misinterpreted the problem requirements (most likely).
  2. The problem requirements are wrong for some reason.
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

In lines 75-79, you unconditionally delete the head if it's the only node in the list. What if id != head->st.id in that case? As for successfully deleting the first node when it matches the id, consider adding another clause between lines 79 and 80 that handles a true deletion of a matching head:

else if (id == head->st.id)
{
    tmp = head;
    head = head->link;
    delete tmp;
}

This will reseat the head to the 2nd node in the list, and then release memory for the old head.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I don't have a solution, but I do know it would be complicated

If you don't know of a solution, how do you know it would be complicated? ;)

I've learnt never to assume something is impossible in the land of programming.

That's not a bad thing, though in this case it is indeed impossible without introducing assumptions about the contents of the array or relying on non-portable solutions. Note that I'm making the same hedge about the unknown here. While I'm not aware of a platform-specific hack that would give you the size of an array through a pointer to its first element, I can't confidently say that no such solution exists.

while (v[i] < 2147483648 && v[i] > -2147483647)

I suspect you believe that this loop works because 2147483648 is overflowing a signed int and wrapping around to INT_MIN on your implementation. When I test the code on Visual Studio 2012 (Windows 7), v[5] is -858993460. The maximum value for signed int is 2147483647 as well, and by saying 2147483648 the behavior on this implementation is to wrap to -2147483648, which is certainly less than -858993460. Thus the loop terminates with the correct result, but certainly not because it's working as intended.

You can break the code by making any value in the array negative.

A more portable loop would be:

while (v[i] < INT_MAX && v[i] > INT_MIN)

But then the bug that caused it to appear to work …

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

But I think it happens even to more experienced people, don't you agree?

Yup, though more experienced people tend to welcome others pointing out such mistakes.

On the other hand, interesting enough that you felt like giving me a lesson instead of simply posting the correct way.

I didn't give you a lesson, I pointed out that your code suggested a distinct lack in your understanding of leap years. Thus I recommended you do some more research. And you'll notice that I did post the correct way, though it was in response to the OP rather than you.

I wonder if it is related to my answers to you by now.

I won't deny that the likelihood of someone responding in an entertaining way affects how I choose to phrase my posts. :D

Hmm... I am wondering what you refer to here? That's because I have no idea what you meant there.

I meant that you made an unwarranted assumption (some might even call it stupid) and gave a common example of another assumption that's equally annoying.

Nevertheless, this conversation gets way out of the subject, don't you think?

The question has been answered. We won't know if the OP needs more help until/if he replies.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

deceptikon, what would be a legitimate keylogger, can you explain what you mean?

Parental control comes to mind, as does corporate activity monitoring, auditing for data entry employees, real-time system recording for backup and replay, and any number of research applications. Moral implications aside, these are all legitimate and legal uses of a keylogger.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Could you explain me what a Keylogger is

A background program than catches and logs keystrokes.

how that kind of software works

It's not especially difficult to intercept keystroke messages, log them, and then pass them on to the intended destination.

how a user can protect from such program?

I assume we're talking about malware and not legitimate keyloggers. If that's the case then you'd protect yourself from keyloggers the way you'd protect yourself from malware in general: firewalls and anti-malware, installing regular updates, safe usage practices, and strong passwords that change often.

Keylogger-specific defenses can get awkward on a PC, such as using a software keyboard instead of a hardware keyboard.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Note that this works fine for char, because char is 1 byte (the size of each element of the array if you will).
If the type were int for example, you need to do a bit of testing forinstance
check that the size of the array is divisible by the type of the array, so as not to exceed its bounds.

I don't understand the point you're trying to make. If you change char to int in your code example, it will still work perfectly:

int arrayX(int * a, int lookfor, int size){
    int found = 0;

    for (int i = 0; i < size; i++){

        if (a[i] == lookfor){

            found++;
        }
    }

    return found;
}

int main()
{
    int a[10] = {'a','b','z','c','z','e','f','g','z','z'};

    cout << arrayX(a,'z',10) << endl;

    return 0;
}

Did you mean only changing lookfor to int and leaving a as a pointer to char?

If you do not know the size of the array, then iy will become much more complicated, but I would not say impossible.

Please describe this "more complicated" solution of finding the size of an array when given nothing but a pointer.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Big words for an admin, don't you think?

As an admin I have to show that I'm a step above the average semiliterate web denizen. I'm sorry if I made you look up any words to figure out what I was saying. ;)

Relax, it was only a joke which wanted to say that I am not working in my calendars with dates so far as year 1900 and I don't expect any of my applications to live for 87 years from now.

I figured that was the case, but it's irrelevant what you need the formula for, and the joke wasn't obvious from your code. If you're posting code as help for someone else, you can't assume that their needs match your needs, especially when your needs are a teeny tiny subset of possible applications.

It's no different than when someone posts code that only compiles under Turbo C++ with the implicit assumption that everyone else uses that compiler. Someone will call you on it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

can't we use a string function pls?

Um...what?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Your findMin() has two problems, one is a bug and another is a usability problem. The bug is that you're moving the pointer ahead by j steps on every recursive call, but you're also using j as an index into the array. This is basically a guaranteed access out of bounds. Either use j to access the array, or move the pointer ahead by 1 each time:

/* Option 1: Use a static index */
int findMin(int *arr, int min, int size)
{
    printf("in findMin() : passed values >> array:%d  min:%d  size:%d\n", *(arr), min, size);

    static int j = 1;

    if (j == size){
        return min; 
    }
    else if (min > arr[j]){
        min = arr[j++];
        return findMin(arr, min, size);  
    }
    else {
        j++;
        return findMin(arr, min, size);
    }
}

/* Option 2: Adjust the pointer */
int findMin(int *arr, int min, int size)
{
    printf("in findMin() : passed values >> array:%d  min:%d  size:%d\n", *(arr), min, size);

    if (size == 0)
        return min; 

    if (min > *arr)
        min = *arr;

    return findMin(arr + 1, min, size - 1);
}

The second option is recommended because using a static variable makes your function non-reentrant. In other words, you can only find the minimum element of an array one time. Any subsequent calls will continue to increment the index. That issue with the static variable is your usability problem.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What is the simplest way to do this?

It's not a matter of simple or not, it's a matter of possible or not. If you're not given a size, can't assume a size, and there's no sentinel value marking the end of the array then you're shit out of luck. In the general case, it's simply not possible to determine the size of an array when all you have is a pointer to the first element.

You seem to be missing key information to solve this problem, such as how is the array set up? Are the items in random order or are they sorted somehow? Is there a sentinel value marking the end? You should probably go back to the person who gave you the assignment and ask for details.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I still have time until 2100 when my formula will blow up. And, definitely, I am not that old to know how was in 1900. ;)

No offense, but that's the most asinine thing I've read all day.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Now that I've converted the formula over to C++ it's not working out.

It's the wrong formula. This is correct:

bool is_leap_year(int year)
{
     return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}

if ( year % 4 == 0 ) return true;

You might want to read up on leap years.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What is the benifit to classes?

They help with the organization of large projects.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

also will the answer be same even i declare the array dynamically??

The results will typically be worse when accessing dynamically allocated memory out of bounds.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You neglected to open fin.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Please ask a specific question. Guessing what kind of "help" you want will result in a lot of wasted time and frustration.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Using dynamic_cast won't compile. Using static_cast will compile

Ah, I misread it as dynamic_cast. My bad.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Also, all the advice in this thread is not wrong

Your most recent post is factually correct (but potentially problematic depending on the format of the file). My previous post is factually correct. Everything prior to that is either flat out wrong or incomplete to the point of being wrong. You can choose which one applies to each post.

If you can't see the wrongness, please consider that you might not be in the best position to help others, and don't be afraid to defer to those who know what they're talking about.

and there is nothing wrong with using c style strings if you wish to.

I never said it was wrong. I said it was awkward, low level, and easy to mess up. If you wish to make things harder on yourself by using a more advanced approach when you lack the experience to do it right, that's your own business. But it would be negligent of me to not mention clearly superior alternatives.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Now, there is no way to esure safety, and this is a potential unsafe operation.(if the pointer tries to access data from Derived)

It's completely safe...because it won't compile. ;)

I feel i am missing something here. Why is there no way in C++ to ensure the safety in this case?

The entire concept is inherently unsafe. Why are you trying to downcast a pointer to non-polymorphic type?

The idea of polymorphism is that you have a base class reference that may or may not have a "real" type of a derived class. You can call derived class overloads through that reference without having to know what the "real" type is. Provided you only use the interface provided by the base class, you don't need any kind of special provisions for derived class objects.

If the classes aren't polymorphic then it doesn't matter what the "real" type is. You'll be slicing that object through a base class reference in all cases. No magic happens to keep you from corrupting derived class objects by pretending that they're base class objects.

myk45 commented: thanks! +5