Thread: Overrriding

  1. #1
    System Novice siavoshkc's Avatar
    Join Date
    Jan 2006
    Location
    Tehran
    Posts
    1,246

    Question Overrriding

    Code:
    class A
    {
    
        public virtual void bmet()
        {
            Console.WriteLine("Base");
        }
    }
    
    class B : A
    {
        public override void bmet()
        {
            Console.WriteLine("Instance");
        }
    }
    
    class C : B
    {
        public void cmet()
        {
            bmet();
            base.bmet(); //This should print Base, no?
        }
    
    }
    Learn C++ (C++ Books, C Books, FAQ, Forum Search)
    Code painter latest version on sourceforge DOWNLOAD NOW!
    Download FSB Data Integrity Tester.
    Siavosh K C

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >base.bmet(); //This should print Base, no?
    Why would it? The base of C is B, not A, and B overrides bmet to print "Instance".
    My best code is written with the delete key.

  3. #3
    System Novice siavoshkc's Avatar
    Join Date
    Jan 2006
    Location
    Tehran
    Posts
    1,246
    I think I concluded wrongly from one of MSDN statements. It was meant in class B you can access base.bmet(). Sorry.
    Learn C++ (C++ Books, C Books, FAQ, Forum Search)
    Code painter latest version on sourceforge DOWNLOAD NOW!
    Download FSB Data Integrity Tester.
    Siavosh K C

  4. #4
    Registered User
    Join Date
    Mar 2005
    Posts
    135
    This stuff can be very confusing to beginners learning polymorphism...
    Here's a basic low-down of your code:

    Each class can represent an object. In class C when you invoke bmet();, your code actually becomes: this.bmet();. the keyword this is the current object - of type C. It's calling the inherited method, bmet();, which, was overridden in the base class (B), thus, the print out should read: "Instance". Otherwise it would print "Base" if not overridden.

    The second line: base.bmet();, the keyword base represents the last object you inherited from (B in your case). Since the base method (or, class B method) is overridden before being inherited by class C, your C object will print out: "Instance" as well.

    - xeddiex

Popular pages Recent additions subscribe to a feed